-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
260 lines (218 loc) · 6.68 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
_ "embed"
"encoding/json"
"html/template"
"net/http"
"net/mail"
"os"
"regexp"
"strings"
log "github.com/sirupsen/logrus"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
const DEFAULT_LISTEN = ":8080"
const DEFAULT_DATABASE_FILE = "nivenly-clae.db"
type Contributor struct {
gorm.Model
LegalName string
Email string
GithubUsername string `gorm:"index:idx_ghuser"`
Agreed bool
RemoteAddr string
}
func main() {
var err error
log.Infof("Starting clae")
dbfile := DEFAULT_DATABASE_FILE
if len(os.Getenv("DATABASE")) > 0 {
dbfile = os.Getenv("DATABASE")
}
listen := DEFAULT_LISTEN
if len(os.Getenv("LISTEN")) > 0 {
listen = os.Getenv("LISTEN")
}
clae := CLAE{}
log.Infof("Connecting to sqlite")
clae.DB, err = gorm.Open(sqlite.Open(dbfile), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
log.Fatalf("Cannot open sqlite db: %v", err)
}
err = clae.DB.AutoMigrate(&Contributor{})
if err != nil {
log.Fatalf("AutoMigrate failed: %v", err)
}
http.HandleFunc("/", clae.FormHandler)
http.HandleFunc("/logo", LogoHandler)
http.HandleFunc("/contributor", clae.ContributorHandler)
http.HandleFunc("/dump", clae.DumpHandler)
log.Infof("listening on %s", listen)
http.ListenAndServe(listen, nil)
}
//go:embed html/nivenly.png
var logo []byte
func LogoHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write(logo)
}
type CLAE struct {
DB *gorm.DB
}
func (c *CLAE) FormHandler(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
// Note: the "Novaproxy-For" header is a value set on Alice in the water tower!
if forwardedFor := r.Header.Get("Novaproxy-For"); len(forwardedFor) > 0 {
remoteAddr = forwardedFor
}
switch r.Method {
case http.MethodGet:
renderForm(w, "")
break
case http.MethodPost:
if len(r.FormValue("legalname")) > 128 {
log.WithField("RemoteAddr", remoteAddr).Infof("legal name too long")
renderForm(w, "Legal name too long (max 128 chars)")
return
}
if len(r.FormValue("email")) > 128 {
log.WithField("RemoteAddr", remoteAddr).Infof("email too long")
renderForm(w, "Email too long (max 128 chars)")
return
}
if _, err := mail.ParseAddress(r.FormValue("email")); err != nil {
log.WithField("RemoteAddr", remoteAddr).Infof("email did not parse; %v", err)
renderForm(w, "Invalid email address")
return
}
if len(r.FormValue("ghusername")) > 128 {
log.WithField("RemoteAddr", remoteAddr).Infof("github username too long")
renderForm(w, "GitHub Username too long (max 128 chars)")
return
}
rx, _ := regexp.Compile("[a-zA-Z0-9-_]*")
if !rx.MatchString(r.FormValue("ghusername")) {
log.WithField("RemoteAddr", remoteAddr).Infof("github name didn't match regex")
renderForm(w, "Invalid GitHub Username")
return
}
resp, err := http.Get("https://github.com/" + r.FormValue("ghusername"))
if err != nil || resp.StatusCode != 200 {
log.WithField("RemoteAddr", remoteAddr).Infof("invalid github username")
renderForm(w, "Invalid GitHub Username")
return
}
if r.FormValue("agreed-source") != "on" || r.FormValue("agreed-content") != "on" {
log.WithField("RemoteAddr", remoteAddr).Infof("did not accept CLA")
renderForm(w, "Please tick the checkboxes to agree to both the CLA \"source code\" and \"content\" terms.")
return
}
cont := Contributor{
LegalName: r.FormValue("legalname"),
Email: r.FormValue("email"),
GithubUsername: r.FormValue("ghusername"),
Agreed: true,
RemoteAddr: remoteAddr,
}
txres := c.DB.Save(&cont)
if err := txres.Error; err != nil {
log.Errorf("Could not save to database: %v", err)
renderForm(w, "Internal Server Error")
return
}
log.WithField("RemoteAddr", remoteAddr).Infof("%s signed the CLA", cont.GithubUsername)
renderOK(w, "")
break
default:
w.WriteHeader(405)
}
}
func (c *CLAE) DumpHandler(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
if forwardedFor := r.Header.Get("Novaproxy-For"); len(forwardedFor) > 0 {
remoteAddr = forwardedFor
}
providedToken := strings.TrimSpace(r.URL.Query().Get("token"))
expectedToken := strings.TrimSpace(os.Getenv("TOKEN"))
if providedToken != expectedToken {
log.WithFields(log.Fields{"RemoteAddr": remoteAddr}).Errorf("invalid token for GET /dump")
w.WriteHeader(403)
return
}
results := []Contributor{}
txres := c.DB.Find(&results)
if err := txres.Error; err != nil {
log.Errorf("Could not query database for contributors: %v", err)
w.WriteHeader(500)
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
err := enc.Encode(results)
if err != nil {
log.Errorf("Could not marshal github usernames: %v", err)
w.WriteHeader(500)
}
}
func (c *CLAE) ContributorHandler(w http.ResponseWriter, r *http.Request) {
remoteAddr := r.RemoteAddr
if forwardedFor := r.Header.Get("Novaproxy-For"); len(forwardedFor) > 0 {
remoteAddr = forwardedFor
}
providedToken := strings.TrimSpace(r.URL.Query().Get("token"))
expectedToken := strings.TrimSpace(os.Getenv("TOKEN"))
if providedToken != expectedToken {
log.WithField("RemoteAddr", remoteAddr).Errorf("invalid token for GET /contributor")
w.WriteHeader(403)
return
}
res := map[string]bool{}
ghname := r.URL.Query().Get("checkContributor")
if len(ghname) < 1 || len(ghname) > 128 {
log.Errorf("invalid checkContributor URL param")
w.WriteHeader(400)
return
}
rx, _ := regexp.Compile("[a-zA-Z0-9-_]*")
if !rx.MatchString(r.FormValue("ghusername")) {
log.Errorf("invalid checkContributor GH username")
w.WriteHeader(400)
return
}
cont := Contributor{}
txres := c.DB.Where("github_username LIKE ?", ghname).First(&cont)
res["isContributor"] = true
if err := txres.Error; err != nil {
log.Errorf("Could not find contributor: %v", err)
res["isContributor"] = false
}
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(res)
if err != nil {
log.Errorf("Could not marshal github usernames: %v", err)
w.WriteHeader(500)
}
}
func renderForm(w http.ResponseWriter, errMsg string) {
tmpl, err := template.ParseFiles("html/form.html")
if err != nil {
log.Errorf("Could not read html/form.html")
w.WriteHeader(500)
w.Write([]byte("Internal Server Error"))
}
w.WriteHeader(200)
tmpl.Execute(w, map[string]string{"ErrMsg": errMsg})
}
func renderOK(w http.ResponseWriter, redirectUrl string) {
tmpl, err := template.ParseFiles("html/ok.html")
if err != nil {
log.Errorf("Could not read html/ok.html")
w.WriteHeader(500)
w.Write([]byte("Internal Server Error"))
}
w.WriteHeader(200)
tmpl.Execute(w, map[string]string{"RedirectUrl": redirectUrl})
}