This repository has been archived by the owner on Oct 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
account.go
340 lines (323 loc) · 13.1 KB
/
account.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package main
import (
"fmt"
"html/template"
"log"
"net"
"net/http"
"github.com/jackc/pgx/v4"
)
const (
templateLogin = "login"
templateLoginFormUsername = "username"
templateLoginFormPassword = "password"
)
func loginHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if !checkFormParse(w, r) {
return
}
log.Printf("Login attempt: [%s]", r.PostFormValue(templateLoginFormUsername))
if !validatePassword(r.PostFormValue(templateLoginFormPassword)) {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginError": true})
return
}
var passdb string
var iddb int
var terminated bool
var username string
derr := dbpool.QueryRow(r.Context(), "SELECT username, password, id, terminated FROM accounts WHERE username = $1 or email = $1", r.PostFormValue("username")).Scan(&username, &passdb, &iddb, &terminated)
if derr != nil {
if derr == pgx.ErrNoRows {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginError": true})
log.Printf("No such user")
} else {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginError": true, "LoginDetailedError": "Database query error: " + derr.Error()})
log.Printf("DB err: " + derr.Error())
}
return
}
if comparePasswords(passdb, r.PostFormValue("password")) {
if terminated {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginError": true,
"LoginDetailedError": template.HTML("<p><b>Account was terminated.</b></p><p><a href=\"/about#contact\">Contact administrator</a> for further information.</p><p>Creating more accounts will not help and will only get you permanently banned.</p>")})
log.Printf("Terminated account [%s] success login attempt", username)
return
}
sessionManager.Put(r.Context(), "User.Username", username)
sessionManager.Put(r.Context(), "User.Id", iddb)
sessionManager.Put(r.Context(), "UserAuthorized", "True")
w.Header().Set("Refresh", "1; /account")
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginComplete": true, "User": map[string]any{"Username": username}})
log.Printf("Log in success: [%s]", username)
} else {
basicLayoutLookupRespond("login", w, r, map[string]any{"LoginError": true})
}
} else {
if r.Header.Get("CF-Visitor") != "{\"scheme\":\"https\"}" {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"WarningUnsafe": true})
} else {
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{})
}
}
}
func terminatedHandler(w http.ResponseWriter, r *http.Request) {
sessionManager.Destroy(r.Context())
w.Header().Set("Refresh", "2; /login")
w.Header().Set("Clear-Site-Data", `"cache", "cookies", "storage", "executionContexts"`)
basicLayoutLookupRespond(templateLogin, w, r, map[string]any{"LoginError": true,
"LoginDetailedError": template.HTML("<p><b>Account was terminated.</b></p><p><a href=\"/about#contact\">Contact administrator</a> for further information.</p><p>Creating more accounts will not help and will only get you permanently banned.</p>")})
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
sessionManager.Destroy(r.Context())
w.Header().Set("Refresh", "2; /login")
w.Header().Set("Clear-Site-Data", `"cache", "cookies", "storage", "executionContexts"`)
basicLayoutLookupRespond("logout", w, r, map[string]any{})
}
func checkIPMatchesConfig(ip string, confpath ...string) bool {
clip := net.ParseIP(ip)
if clip == nil {
return false
}
ipmatchs := map[string]bool{}
o, ok := cfg.GetKeys(confpath...)
if !ok {
return false
}
for _, k := range o {
s, ok := cfg.GetBool(append(confpath, k)...)
if !ok {
return false
}
if !s {
delete(ipmatchs, k)
} else {
ipmatchs[k] = s
}
}
for kip, v := range ipmatchs {
if !v {
continue
}
_, pnt, err := net.ParseCIDR(kip)
if err != nil {
log.Printf("ipmatch ip %q is not in CIDR notation: %s", kip, err)
continue
}
if pnt == nil {
log.Printf("ipmatch ip %q has no network after parsing", kip)
continue
}
if pnt.Contains(clip) {
log.Printf("ipmatch applied to client %q with rule %q", ip, kip)
return true
}
}
return false
}
func registerHandler(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("CF-Connecting-IP")
if ip == "" {
ip = r.RemoteAddr
}
if checkIPMatchesConfig(ip, "ipnoreg") {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "You are not allowed to create accounts. Contact administration."})
return
}
if r.Method == http.MethodPost {
err := r.ParseForm()
if err != nil {
log.Printf("Error reading form: %v\n", err)
return
}
type LastAttemptS struct {
Username string
Password string
Email string
}
la := LastAttemptS{r.PostFormValue("username"), r.PostFormValue("password"), r.PostFormValue("email")}
if !validateUsername(r.PostFormValue("username")) {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Username length must be between 3 and 25 and not contain '@' character", "LastAttempt": la})
return
}
if !validatePassword(r.PostFormValue("password")) {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Password length must be between 6 and 25", "LastAttempt": la})
return
}
if r.PostFormValue("password") != r.PostFormValue("confirm-password") {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Passwords are not matching", "LastAttempt": la})
return
}
if !validateEmail(r.PostFormValue("email")) {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Email is not valid", "LastAttempt": la})
return
}
requname := r.PostFormValue("username")
requpass := hashPassword(r.PostFormValue("password"))
reqemail := r.PostFormValue("email")
reqemailcode := generateRandomString(50)
log.Printf("Register attempt: [%s] [%s]", requname, reqemail)
dberr := func(e error) {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Database call error: " + e.Error(), "LastAttempt": la})
}
numUsername := 0
numUsernameErr := dbpool.QueryRow(r.Context(), "SELECT COUNT(*) FROM accounts WHERE username = $1", requname).Scan(&numUsername)
if numUsernameErr != nil {
dberr(numUsernameErr)
return
}
if numUsername != 0 {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Username is already taken!", "LastAttempt": la})
return
}
numEmail := 0
numEmailErr := dbpool.QueryRow(r.Context(), "SELECT COUNT(*) FROM accounts WHERE email = $1", reqemail).Scan(&numEmail)
if numEmailErr != nil {
dberr(numEmailErr)
return
}
if numEmail != 0 {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Email is already taken!", "LastAttempt": la})
return
}
if err := sendgridConfirmcode(reqemail, reqemailcode); err != nil {
log.Println("Failed to send email: ", err)
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Can't verify email. Contact administrator.", "LastAttempt": la})
return
}
tag, derr := dbpool.Exec(r.Context(), "INSERT INTO accounts (username, password, email, email_confirm_code) VALUES($1, $2, $3, $4) ON CONFLICT DO NOTHING", requname, requpass, reqemail, reqemailcode)
if derr != nil {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Database call error: " + derr.Error(), "LastAttempt": la})
return
}
if tag.RowsAffected() != 1 {
basicLayoutLookupRespond("register", w, r, map[string]any{"RegisterErrorMsg": "Database insert error, rows affected " + string(tag), "LastAttempt": la})
return
}
basicLayoutLookupRespond("register", w, r, map[string]any{"SuccessRegister": true})
log.Printf("Register attempt success: [%s] [%s]", requname, reqemail)
sendWebhook(cfg.GetDSString("", "webhooks", "actions"), fmt.Sprintf(`New account registered %q`, requname))
} else {
if r.Header.Get("CF-Visitor") != "{\"scheme\":\"https\"}" {
basicLayoutLookupRespond("register", w, r, map[string]any{"WarningUnsafe": true})
} else {
basicLayoutLookupRespond("register", w, r, map[string]any{})
}
}
}
func emailconfHandler(w http.ResponseWriter, r *http.Request) {
keys, ok := r.URL.Query()["code"]
if !ok || len(keys) == 0 || len(keys[0]) < 1 || keys[0] == "resetcomplete" {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Confirm code does not exist", "msgred": true})
return
}
key := keys[0]
tag, derr := dbpool.Exec(r.Context(), "UPDATE accounts SET email_confirmed = now(), email_confirm_code = '' WHERE email_confirm_code = $1", key)
if derr != nil {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Database call error: " + derr.Error(), "msgred": true})
return
}
if tag.RowsAffected() != 1 {
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Confirm code does not exist", "msgred": true})
return
}
basicLayoutLookupRespond("plainmsg", w, r, map[string]any{"msg": "Email confirmed.", "msggreen": true})
}
func recoverPasswordHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Printf("Error reading form: %v", err)
return
}
if r.PostFormValue("reset") == "yes" {
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.Printf("Error reading form: %v", err)
return
}
log.Printf("code [%v]", r.PostFormValue("code"))
log.Printf("password [%v]", r.PostFormValue("password"))
log.Printf("password-confirm [%v]", r.PostFormValue("password-confirm"))
log.Printf("reset [%v]", r.PostFormValue("reset"))
if r.PostFormValue("code") == "resetcomplete" || r.PostFormValue("code") == "" || r.PostFormValue("password") == "" {
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverError": true})
return
}
if r.PostFormValue("password") != r.PostFormValue("password-confirm") {
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverDetailedError": "Passwords don't match"})
return
}
if !validatePassword(r.PostFormValue("password")) {
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverDetailedError": "Password must be between 6 and 25 symbols in length"})
return
}
tag, derr := dbpool.Exec(r.Context(), "UPDATE accounts SET password = $1, email_confirm_code = 'resetcomplete' WHERE email_confirm_code = $2", hashPassword(r.PostFormValue("password")), r.PostFormValue("code"))
if derr != nil {
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverError": true})
log.Print(derr)
return
}
if tag.RowsAffected() != 1 {
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverError": true})
log.Print("No such recovery code")
return
}
log.Print("Password recovery attempt SUCCESS")
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoverComplete": true})
w.Header().Set("Refresh", "5; /login")
} else {
if !validateEmail(r.PostFormValue("email")) {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
return
}
reqTerminated := false
err := dbpool.QueryRow(r.Context(), "SELECT terminated FROM accounts WHERE email = $1 AND coalesce(extract(epoch from email_confirmed), 0) != 0", r.PostFormValue("email")).Scan(&reqTerminated)
if err != nil {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
log.Print(err)
return
}
if reqTerminated {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
return
}
reqemailcode := generateRandomString(50)
tag, derr := dbpool.Exec(r.Context(), "UPDATE accounts SET email_confirm_code = $1 WHERE email = $2", reqemailcode, r.PostFormValue("email"))
if derr != nil {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
log.Print(derr)
return
}
if tag.RowsAffected() != 1 {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
return
}
log.Printf("Password recovery attempt [%s]", r.PostFormValue("email"))
sendgridRecoverRequest(r.PostFormValue("email"), reqemailcode)
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverComplete": true, "Email": r.PostFormValue("email")})
}
} else {
keys, ok := r.URL.Query()["code"]
if !ok || len(keys[0]) < 1 {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{})
log.Print("No code")
return
}
numEmails := 0
numEmailsErr := dbpool.QueryRow(r.Context(), "SELECT COUNT(*) FROM accounts WHERE email_confirm_code = $1", keys[0]).Scan(&numEmails)
if numEmailsErr != nil {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
log.Print(numEmailsErr)
return
}
if numEmails != 1 {
basicLayoutLookupRespond("recoveryRequest", w, r, map[string]any{"RecoverError": true})
log.Print("No email", numEmails)
return
}
basicLayoutLookupRespond("passwordReset", w, r, map[string]any{"RecoveryCode": keys[0]})
}
}