/
auth.go
347 lines (314 loc) · 7.42 KB
/
auth.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
341
342
343
344
345
346
347
package server
import (
"database/sql"
"net/http"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/cutechan/cutechan/go/auth"
"github.com/cutechan/cutechan/go/common"
"github.com/cutechan/cutechan/go/config"
"github.com/cutechan/cutechan/go/db"
"golang.org/x/crypto/bcrypt"
)
var (
userIDRe = regexp.MustCompile(`^[-_ \p{Latin}\p{Cyrillic}\d]+$`)
)
type loginCreds struct {
ID, Password string
auth.Captcha
}
type passwordChangeRequest struct {
Old, New string
auth.Captcha
}
// Register a new user account
func register(w http.ResponseWriter, r *http.Request) {
var req loginCreds
isValid := decodeJSON(w, r, &req) &&
trimUserID(&req.ID) &&
validateUserID(w, req.ID) &&
checkPasswordAndCaptcha(w, r, req.Password, req.Captcha)
if !isValid {
return
}
hash, err := auth.BcryptHash(req.Password, 10)
if err != nil {
text500(w, r, err)
}
// Check for collision and write to DB
switch err := db.RegisterAccount(req.ID, hash); err {
case nil:
case db.ErrUserNameTaken:
text400(w, errUserIDTaken)
return
default:
text500(w, r, err)
return
}
commitLogin(w, r, req.ID)
}
func checkUserID(id string) bool {
return id != "" &&
utf8.RuneCountInString(id) <= common.MaxLenUserID &&
userIDRe.MatchString(id)
}
func validateUserID(w http.ResponseWriter, id string) bool {
if !checkUserID(id) {
text400(w, aerrInvalidUserID)
return false
}
return true
}
// If login successful, generate a session token and commit to DB. Otherwise
// write error message to client.
func commitLogin(w http.ResponseWriter, r *http.Request, userID string) {
token, err := auth.RandomID(128)
if err != nil {
text500(w, r, err)
return
}
if err := db.WriteLoginSession(userID, token); err != nil {
text500(w, r, err)
return
}
// One hour less, so the cookie expires a bit before the DB session
// gets deleted.
expiry := time.Duration(common.SessionExpiry)*time.Hour*24 - time.Hour
expires := time.Now().Add(expiry)
sessionCookie := http.Cookie{
Name: "session",
Value: token,
Path: "/",
Expires: expires,
Secure: secureCookie,
HttpOnly: true,
}
setSameSiteCookie(w, &sessionCookie, SAMESITE_LAX_MODE)
}
// Log into a registered user account
func login(w http.ResponseWriter, r *http.Request) {
var req loginCreds
switch {
case !decodeJSON(w, r, &req):
return
case !trimUserID(&req.ID):
return
case !auth.AuthenticateCaptcha(req.Captcha):
text403(w, errInvalidCaptcha)
return
}
hash, err := db.GetPassword(req.ID)
switch err {
case nil:
case sql.ErrNoRows:
text403(w, common.ErrInvalidCreds)
return
default:
text500(w, r, err)
return
}
switch err := auth.BcryptCompare(req.Password, hash); err {
case nil:
commitLogin(w, r, req.ID)
case bcrypt.ErrMismatchedHashAndPassword:
text403(w, common.ErrInvalidCreds)
default:
text500(w, r, err)
}
}
// Common part of both logout endpoints
func commitLogout(
w http.ResponseWriter,
r *http.Request,
fn func(*http.Request, *auth.Session) error,
) {
ss := assertSession(w, r, "")
if ss == nil {
return
}
if err := fn(r, ss); err != nil {
text500(w, r, err)
return
}
expires := time.Unix(0, 0)
sessionCookie := http.Cookie{
Name: "session",
Value: "0",
Path: "/",
Expires: expires,
Secure: secureCookie,
HttpOnly: true,
}
setSameSiteCookie(w, &sessionCookie, SAMESITE_LAX_MODE)
}
// Log out user from session and remove the session key from the database
func logout(w http.ResponseWriter, r *http.Request) {
commitLogout(w, r, func(r *http.Request, ss *auth.Session) error {
token, err := getLoginToken(r)
if err != nil {
return err
}
return db.LogOut(ss.UserID, token)
})
}
// Log out all sessions of the specific user
func logoutAll(w http.ResponseWriter, r *http.Request) {
commitLogout(w, r, func(r *http.Request, ss *auth.Session) error {
return db.LogOutAll(ss.UserID)
})
}
// Change the account password
func changePassword(w http.ResponseWriter, r *http.Request) {
var msg passwordChangeRequest
if !decodeJSON(w, r, &msg) {
return
}
ss := assertSession(w, r, "")
if ss == nil || !checkPasswordAndCaptcha(w, r, msg.New, msg.Captcha) {
return
}
// Get old hash
hash, err := db.GetPassword(ss.UserID)
if err != nil {
text500(w, r, err)
return
}
// Validate old password
switch err := auth.BcryptCompare(msg.Old, hash); err {
case nil:
case bcrypt.ErrMismatchedHashAndPassword:
text403(w, common.ErrInvalidCreds)
return
default:
text500(w, r, err)
return
}
// Old password matched, write new hash to DB
hash, err = auth.BcryptHash(msg.New, 10)
if err != nil {
text500(w, r, err)
return
}
if err := db.ChangePassword(ss.UserID, hash); err != nil {
text500(w, r, err)
}
}
// Check password length and authenticate captcha, if needed
func checkPasswordAndCaptcha(
w http.ResponseWriter,
r *http.Request,
password string,
captcha auth.Captcha,
) bool {
switch {
case password == "", len(password) > common.MaxLenPassword:
text400(w, errInvalidPassword)
return false
case !auth.AuthenticateCaptcha(captcha):
text403(w, errInvalidCaptcha)
return false
}
return true
}
// Trim spaces from userID. Chainable with other authenticators.
func trimUserID(id *string) bool {
*id = strings.TrimSpace(*id)
return true
}
func getLoginToken(r *http.Request) (string, error) {
c, err := r.Cookie("session")
if err != nil {
return "", common.ErrInvalidCreds
}
token := c.Value
if len(token) != common.LenSession {
return "", common.ErrInvalidCreds
}
return token, nil
}
// Get request session data if any.
func getSession(r *http.Request, board string) (ss *auth.Session, err error) {
token, err := getLoginToken(r)
if err != nil {
return
}
// Just in case, to avoid search for invalid board in DB.
if board != "" && !config.IsBoard(board) {
err = errInvalidBoard
return
}
// FIXME(Kagami): This might be affected to timing attack.
return db.GetSession(board, token)
}
// Assert the user login session ID is valid.
func assertSession(w http.ResponseWriter, r *http.Request, b string) *auth.Session {
ss, err := getSession(r, b)
switch err {
case nil:
// Do nothing.
case common.ErrInvalidCreds:
text403(w, err)
default:
text500(w, r, err)
}
return ss
}
func serverSetAccountSettings(w http.ResponseWriter, r *http.Request) {
ss := assertSession(w, r, "")
if ss == nil {
return
}
err := setAccountSettings(r, ss)
if err != nil {
serveErrorJSON(w, r, err)
return
}
serveEmptyJSON(w, r)
}
// FIXME(Kagami): Don't mix text/plain and application/json errors.
func setAccountSettings(r *http.Request, ss *auth.Session) (err error) {
var as auth.AccountSettings
if err = readJSON(r, &as); err != nil {
return
}
trimUserID(&as.Name)
if !checkUserID(as.Name) {
return aerrInvalidUserID
}
if len(as.Whitelist) > common.MaxLenIgnoreList ||
len(as.Blacklist) > common.MaxLenIgnoreList {
return aerrTooManyIgnores
}
ignores := make(map[string]bool)
for _, id := range as.Whitelist {
// Don't bother matching against DB values. It's their problem if
// they passed wrong user IDs.
if !checkUserID(id) {
return aerrInvalidUserID
}
if ignores[id] {
return aerrDupIgnores
}
ignores[id] = true
}
for _, id := range as.Blacklist {
if !checkUserID(id) {
return aerrInvalidUserID
}
if ignores[id] {
return aerrDupIgnores
}
ignores[id] = true
}
err = db.SetAccountSettings(ss.UserID, as)
switch err {
case nil:
return
case db.ErrUserNameTaken:
return aerrNameTaken
default:
return aerrInternal.Hide(err)
}
}