-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.go
390 lines (363 loc) · 9.76 KB
/
local.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2021-2024 The HeyApple Authors.
//
// Use of this source code is governed by the GNU Affero General
// Public License as published by the Free Software Foundation,
// either version 3 of the License, or any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////
package auth
import (
"context"
"net/http"
"github.com/and-rad/heyapple/internal/app"
"github.com/and-rad/heyapple/internal/handler"
"github.com/and-rad/scs/v2"
"github.com/julienschmidt/httprouter"
)
// Confirm completes the user registration by confirming
// the sign-up token. If successful, the associated token
// is deleted and the user is able to sign in. The
// response body is always empty.
//
// Endpoint:
//
// /auth/confirm
//
// Methods:
//
// PUT
//
// Possible status codes:
//
// 200 - Registration complete
// 400 - Malformed or missing form data
// 404 - User or token doesn't exist
// 500 - Internal server error
//
// Example input:
//
// token=178a6ee3f1da299fed940aa2d7
func Confirm(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
cmd := &app.Activate{Token: r.FormValue("token")}
if cmd.Token == "" {
w.WriteHeader(http.StatusBadRequest)
} else if err := env.DB.Execute(cmd); err == app.ErrNotFound {
w.WriteHeader(http.StatusNotFound)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
// LocaLogin handles login for users with local accounts
// as opposed to users who authenticate with SSO services
// like OAuth. The response body is always empty.
//
// Endpoint:
//
// /auth/local
//
// Methods:
//
// POST
//
// Possible status codes:
//
// 200 - Login successful
// 400 - Malformed or missing form data
// 401 - Unsuccessful login attempt
// 500 - Internal server error
//
// Example input:
//
// email=user@example.com&pass=topsecret
func LocalLogin(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
query := &app.Authenticate{
Email: r.FormValue("email"),
Pass: r.FormValue("pass"),
}
if query.Email == "" || query.Pass == "" {
w.WriteHeader(http.StatusBadRequest)
} else if err := env.DB.Fetch(query); err == app.ErrCredentials {
w.WriteHeader(http.StatusUnauthorized)
} else if err == app.ErrNotFound {
w.WriteHeader(http.StatusUnauthorized)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
env.Session.Put(r.Context(), "id", query.ID)
env.Session.Put(r.Context(), "lang", query.Lang)
env.Session.Put(r.Context(), "perm", query.Perm)
}
}
}
// LocaLogout handles logout for users with local accounts
// as opposed to users who authenticate with SSO services
// like OAuth. The response body is always empty.
//
// Endpoint:
//
// /auth/local
//
// Methods:
//
// DELETE
//
// Possible status codes:
//
// 200 - Logout successful
// 404 - Session not found, user is not logged in
// 500 - Internal server error
func LocalLogout(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if err := env.Session.Destroy(r.Context()); err == scs.ErrNoSession {
w.WriteHeader(http.StatusNotFound)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
// ResetRequest creates a new password reset request and
// sends a notification to the user with instructions
// on how to complete the request. The response body is
// always empty. For security reasons, this is one of a handful
// of functions that return success status codes even when
// technically failing. This is done to make user enumeration
// more difficult.
//
// Endpoint:
//
// /auth/reset
//
// Methods:
//
// POST
//
// Possible status codes:
//
// 202 - Request was accepted
// 400 - Malformed or missing form data
// 500 - Internal server error
//
// Example input:
//
// email=user@example.com
func ResetRequest(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
cmd := &app.ResetPassword{Email: r.FormValue("email")}
if cmd.Email == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
err := env.DB.Execute(cmd)
if err == app.ErrNotFound {
w.WriteHeader(http.StatusAccepted)
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
data := app.NotificationData{
"lang": "en",
"token": cmd.Token,
}
err = env.Msg.Send(cmd.Email, app.ResetNotification, data)
if err != nil {
env.Log.Error(err)
}
}
}
// ResetConfirm completes a password reset request. If
// successful, the associated token is deleted and the
// password is changed. The response body is always empty.
//
// Endpoint:
//
// /auth/reset
//
// Methods:
//
// PUT
//
// Possible status codes:
//
// 200 - Password reset successful
// 400 - Malformed or missing form data
// 404 - User or token doesn't exist
// 422 - New password is too weak
// 500 - Internal server error
//
// Example input:
//
// email=user@example.com&pass=topsecret
func ResetConfirm(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
cmd := &app.ChangePassword{
Token: r.FormValue("token"),
Pass: r.FormValue("pass"),
}
if cmd.Token == "" || cmd.Pass == "" {
w.WriteHeader(http.StatusBadRequest)
} else if err := env.DB.Execute(cmd); err == app.ErrNotFound {
w.WriteHeader(http.StatusNotFound)
} else if err == app.ErrWeakPass {
w.WriteHeader(http.StatusUnprocessableEntity)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
// ChangePassword sets a new password for the logged-in user.
// Unlike ResetConfirm, it doesn't require a token, but it
// checks the requesting user's identity and expects the user's
// current password. If successful, the password is changed.
// The response body is always empty.
//
// This is the route that should be called when users try to
// change their passwords from within their profile settings.
//
// Endpoint:
//
// /auth/pass
//
// Methods:
//
// PUT
//
// Possible status codes:
//
// 200 - Password change successful
// 400 - Malformed or missing form data
// 401 - Insufficient permission
// 404 - User doesn't exist
// 422 - New password is too weak
// 500 - Internal server error
//
// Example input:
//
// passold=topsecret&passnew=topsecret123
func ChangePassword(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
old := r.FormValue("passold")
new := r.FormValue("passnew")
if old == "" || new == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
uid, ok := env.Session.Get(r.Context(), "id").(int)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
query := &app.Authorize{ID: uid, Pass: old}
if err := env.DB.Fetch(query); err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else if !query.Ok {
w.WriteHeader(http.StatusUnauthorized)
}
if !query.Ok {
return
}
cmd := &app.ChangePassword{ID: uid, Pass: new}
if err := env.DB.Execute(cmd); err == app.ErrWeakPass {
w.WriteHeader(http.StatusUnprocessableEntity)
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusOK)
}
}
}
// ChangeEmail starts the process of setting a new e-mail
// address for the logged-in user. The change needs to be
// confirmed before it takes effect. The response body is
// always empty.
//
// Endpoint:
//
// /auth/email
//
// Methods:
//
// PUT
//
// Possible status codes:
//
// 202 - Request was accepted
// 400 - Malformed or missing form data
// 401 - Insufficient permission
// 422 - Not a valid e-mail address
// 500 - Internal server error
//
// Example input:
//
// email=new@email.address
func ChangeEmail(env *handler.Environment) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
email := r.FormValue("email")
if email == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
uid, ok := env.Session.Get(r.Context(), "id").(int)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
cmd := &app.RequestEmailChange{ID: uid, Email: email}
err := env.DB.Execute(cmd)
if err == app.ErrExists {
w.WriteHeader(http.StatusAccepted)
return
}
if err == app.ErrNoEmail {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
data := app.NotificationData{
"lang": "en",
"token": cmd.Token,
}
err = env.Msg.Send(cmd.Email, app.RenameNotification, data)
if err != nil {
env.Log.Error(err)
}
}
}
// logOut can be used to invalidate the session that
// belongs to the user identified by id. It should be
// called after making permission changes on that user
// as an extra security step.
func logOut(sm *scs.SessionManager, r *http.Request, id int) error {
return sm.Iterate(r.Context(), func(ctx context.Context) error {
if uid, ok := sm.Get(ctx, "id").(int); ok && uid == id {
return sm.Destroy(ctx)
}
return nil
})
}