forked from LunaNode/lobster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
323 lines (278 loc) · 10 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
package lobster
import "github.com/LunaNode/lobster/utils"
import "golang.org/x/crypto/pbkdf2"
import "crypto/rand"
import "crypto/sha512"
import "crypto/subtle"
import "encoding/hex"
import "fmt"
import "log"
import "net/http"
import "strings"
func authMakePassword(password string) string {
salt := make([]byte, 16)
_, err := rand.Read(salt)
checkErr(err)
passwordHash := pbkdf2.Key([]byte(password), salt, 8192, 64, sha512.New)
return hex.EncodeToString(salt) + ":" + hex.EncodeToString(passwordHash)
}
func authCreate(ip string, username string, password string, email string) (int, error) {
if !AntifloodCheck(ip, "authCreate", 3) {
return 0, L.Error("try_again_later")
}
userId, err := UserCreate(username, password, email)
if err != nil {
return 0, err
}
LogAction(userId, ip, "Registered account", "")
AntifloodAction(ip, "authCreate")
MailWrap(-1, "accountCreated", AccountCreatedEmail{UserId: int(userId), Username: username, Email: email}, false)
return userId, nil
}
func authCheckPassword(password string, actualPasswordCombined string) bool {
// grab salt/password parts
passwordParts := strings.Split(actualPasswordCombined, ":")
salt, _ := hex.DecodeString(passwordParts[0])
actualPasswordHash, _ := hex.DecodeString(passwordParts[1])
// derive key from provided password and match
providedPasswordHash := pbkdf2.Key([]byte(password), salt, 8192, 64, sha512.New)
return subtle.ConstantTimeCompare(actualPasswordHash, providedPasswordHash) == 1
}
func authLogin(ip string, username string, password string) (int, error) {
if len(password) > MAX_PASSWORD_LENGTH {
return 0, L.Error("incorrect_username_or_password")
} else if !AntifloodCheck(ip, "authCheck", 12) {
return 0, L.Error("try_again_later")
}
rows := db.Query("SELECT id, password FROM users WHERE username = ? AND status != 'disabled'", username)
if !rows.Next() {
log.Printf("Authentication failure on user=%s: bad username (%s)", username, ip)
AntifloodAction(ip, "authCheck")
return 0, L.Error("incorrect_username_or_password")
}
var userId int
var actualPasswordCombined string
rows.Scan(&userId, &actualPasswordCombined)
rows.Close()
if authCheckPassword(password, actualPasswordCombined) {
log.Printf("Authentication successful for user=%s (%s)", username, ip)
LogAction(userId, ip, "Logged in", "")
return userId, nil
} else {
AntifloodAction(ip, "authCheck")
log.Printf("Authentication failure on user=%s: bad password (%s)", username, ip)
return 0, L.Error("incorrect_username_or_password")
}
}
func authChangePassword(ip string, userId int, oldPassword string, newPassword string) error {
if len(newPassword) < MIN_PASSWORD_LENGTH || len(newPassword) > MAX_PASSWORD_LENGTH {
return L.Errorf("password_length", MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
} else if !AntifloodCheck(ip, "authCheck", 12) {
return L.Error("try_again_later")
}
rows := db.Query("SELECT password FROM users WHERE id = ?", userId)
if !rows.Next() {
AntifloodAction(ip, "authCheck")
log.Printf("Error changing password: bad user ID?! (%d/%s)", userId, ip)
return L.Error("invalid_account")
}
var actualPasswordCombined string
rows.Scan(&actualPasswordCombined)
rows.Close()
if authCheckPassword(oldPassword, actualPasswordCombined) {
db.Exec("UPDATE users SET password = ? WHERE id = ?", authMakePassword(newPassword), userId)
log.Printf("Successful password change for user_id=%d (%s)", userId, ip)
LogAction(userId, ip, "Change password", "")
MailWrap(userId, "authChangePassword", nil, false)
return nil
} else {
AntifloodAction(ip, "authCheck")
log.Printf("Change password authentication failure for user_id=%d (%s)", userId, ip)
return L.Error("incorrect_password")
}
}
func authForceChangePassword(userId int, password string) {
db.Exec("UPDATE users SET password = ? WHERE id = ?", authMakePassword(password), userId)
}
func authPwresetRequest(ip string, username string, email string) error {
if email == "" {
return L.Error("pwreset_email_required")
} else if !AntifloodCheck(ip, "pwresetRequest", 10) {
return L.Error("try_again_later")
}
AntifloodAction(ip, "pwresetRequest") // mark antiflood regardless of whether success/failure
rows := db.Query("SELECT id FROM users WHERE username = ? AND email = ?", username, email)
if !rows.Next() {
return L.Error("incorrect_username_email")
}
var userId int
rows.Scan(&userId)
rows.Close()
// make sure not already active pwreset for this user
var count int
db.QueryRow("SELECT COUNT(*) FROM pwreset_tokens WHERE user_id = ?", userId).Scan(&count)
if count > 0 {
return L.Error("pwreset_outstanding")
}
token := utils.Uid(32)
db.Exec("INSERT INTO pwreset_tokens (user_id, token) VALUES (?, ?)", userId, token)
MailWrap(userId, "pwresetRequest", token, false)
return nil
}
func authPwresetSubmit(ip string, userId int, token string, password string) error {
if !AntifloodCheck(ip, "pwresetSubmit", 10) {
return L.Error("try_again_later")
} else if len(password) < MIN_PASSWORD_LENGTH || len(password) > MAX_PASSWORD_LENGTH {
return L.Errorf("password_length", MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
}
AntifloodAction(ip, "pwresetSubmit") // mark antiflood regardless of whether success/failure
rows := db.Query("SELECT id FROM pwreset_tokens WHERE user_id = ? AND token = ? AND time > DATE_SUB(NOW(), INTERVAL ? MINUTE)", userId, token, PWRESET_EXPIRE_MINUTES)
if !rows.Next() {
return L.Error("incorrect_token")
}
var tokenId int
rows.Scan(&tokenId)
rows.Close()
db.Exec("DELETE FROM pwreset_tokens WHERE id = ?", tokenId)
db.Exec("UPDATE users SET password = ? WHERE id = ?", authMakePassword(password), userId)
log.Printf("Successful password reset for user_id=%d (%s)", userId, ip)
LogAction(userId, ip, "Reset password", "")
MailWrap(userId, "authChangePassword", nil, false)
return nil
}
type AuthLoginForm struct {
Username string `schema:"username"`
Password string `schema:"password"`
}
func authLoginHandler(w http.ResponseWriter, r *http.Request, session *Session) {
if session.IsLoggedIn() {
RedirectMessage(w, r, "/panel/dashboard", L.Info("already_logged_in"))
return
}
form := new(AuthLoginForm)
err := decoder.Decode(form, r.PostForm)
if err != nil {
http.Redirect(w, r, "/login", 303)
return
}
userId, err := authLogin(ExtractIP(r.RemoteAddr), form.Username, form.Password)
if err != nil {
RedirectMessage(w, r, "/login", L.FormatError(err))
return
} else {
session.UserId = userId
http.Redirect(w, r, "/panel/dashboard", 303)
user := UserDetails(userId)
if user != nil && user.Admin {
session.Admin = true
}
}
}
type AuthCreateForm struct {
Username string `schema:"username"`
Password string `schema:"password"`
Email string `schema:"email"`
AcceptTerms string `schema:"acceptTermsOfService"`
}
func authCreateHandler(w http.ResponseWriter, r *http.Request, session *Session) {
if session.IsLoggedIn() {
RedirectMessage(w, r, "/panel/dashboard", L.Info("already_logged_in"))
return
}
form := new(AuthCreateForm)
err := decoder.Decode(form, r.PostForm)
if err != nil {
http.Redirect(w, r, "/create", 303)
return
}
if form.AcceptTerms != "yes" {
RedirectMessage(w, r, "/create", L.FormattedError("must_terms"))
return
}
userId, err := authCreate(ExtractIP(r.RemoteAddr), form.Username, form.Password, form.Email)
if err != nil {
RedirectMessage(w, r, "/create", L.FormatError(err))
return
} else {
session.UserId = userId
http.Redirect(w, r, "/panel/dashboard", 303)
}
}
func authLogoutHandler(w http.ResponseWriter, r *http.Request, session *Session) {
session.Reset()
http.Redirect(w, r, "/login", 303)
}
type AuthPwresetParams struct {
Title string
Message string
Token string
PwresetUserId string
PwresetToken string
}
func authPwresetHandler(w http.ResponseWriter, r *http.Request, session *Session) {
message := ""
if r.URL.Query()["message"] != nil {
message = r.URL.Query()["message"][0]
}
params := AuthPwresetParams{
Message: message,
Token: CSRFGenerate(session),
}
if r.URL.Query().Get("user_id") != "" && r.URL.Query().Get("token") != "" {
params.PwresetUserId = r.URL.Query().Get("user_id")
params.PwresetToken = r.URL.Query().Get("token")
RenderTemplate(w, "splash", "pwreset_submit", params)
} else {
RenderTemplate(w, "splash", "pwreset_request", params)
}
}
type AuthPwresetRequestForm struct {
Username string `schema:"username"`
Email string `schema:"email"`
}
func authPwresetRequestHandler(w http.ResponseWriter, r *http.Request, session *Session) {
if session.IsLoggedIn() {
RedirectMessage(w, r, "/panel/dashboard", L.Info("already_logged_in"))
return
}
form := new(AuthPwresetRequestForm)
err := decoder.Decode(form, r.PostForm)
if err != nil {
http.Redirect(w, r, "/pwreset", 303)
return
}
err = authPwresetRequest(ExtractIP(r.RemoteAddr), form.Username, form.Email)
if err != nil {
RedirectMessage(w, r, "/pwreset", L.FormatError(err))
return
} else {
RedirectMessage(w, r, "/message", L.Success("pwreset_requested"))
}
}
type AuthPwresetSubmitForm struct {
UserId int `schema:"pwreset_user_id"`
Token string `schema:"pwreset_token"`
Password string `schema:"password"`
PasswordConfirm string `schema:"password_confirm"`
}
func authPwresetSubmitHandler(w http.ResponseWriter, r *http.Request, session *Session) {
if session.IsLoggedIn() {
RedirectMessage(w, r, "/panel/dashboard", L.Info("already_logged_in"))
return
}
form := new(AuthPwresetSubmitForm)
err := decoder.Decode(form, r.PostForm)
if err != nil {
http.Redirect(w, r, "/pwreset", 303)
return
} else if form.Password != form.PasswordConfirm {
RedirectMessageExtra(w, r, "/pwreset", L.FormattedError("password_mismatch"), map[string]string{"user_id": fmt.Sprintf("%d", form.UserId), "token": form.Token})
}
err = authPwresetSubmit(ExtractIP(r.RemoteAddr), form.UserId, form.Token, form.Password)
if err != nil {
RedirectMessageExtra(w, r, "/pwreset", L.FormatError(err), map[string]string{"user_id": fmt.Sprintf("%d", form.UserId), "token": form.Token})
return
} else {
RedirectMessage(w, r, "/message", L.Success("pwreset_completed"))
}
}