/
verification.go
536 lines (473 loc) · 15.2 KB
/
verification.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package handler
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/mediocregopher/radix/v4"
"github.com/pilinux/argon2"
log "github.com/sirupsen/logrus"
"github.com/pilinux/gorest/config"
"github.com/pilinux/gorest/database"
"github.com/pilinux/gorest/database/model"
"github.com/pilinux/gorest/lib"
"github.com/pilinux/gorest/lib/middleware"
"github.com/pilinux/gorest/service"
)
// VerifyEmail handles jobs for controller.VerifyEmail
func VerifyEmail(payload model.AuthPayload) (httpResponse model.HTTPResponse, httpStatusCode int) {
payload.VerificationCode = strings.TrimSpace(payload.VerificationCode)
if payload.VerificationCode == "" {
httpResponse.Message = "required a valid email verification code"
httpStatusCode = http.StatusBadRequest
return
}
data := struct {
key string
value string
}{}
data.key = model.EmailVerificationKeyPrefix + payload.VerificationCode
// get redis client
client := *database.GetRedis()
rConnTTL := config.GetConfig().Database.REDIS.Conn.ConnTTL
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(rConnTTL)*time.Second)
defer cancel()
// is key available in redis
result := 0
if err := client.Do(ctx, radix.FlatCmd(&result, "EXISTS", data.key)); err != nil {
log.WithError(err).Error("error code: 1061.1")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
if result == 0 {
httpResponse.Message = "wrong/expired verification code"
httpStatusCode = http.StatusBadRequest
return
}
// find key in redis
if err := client.Do(ctx, radix.FlatCmd(&data.value, "GET", data.key)); err != nil {
log.WithError(err).Error("error code: 1061.2")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// delete key from redis
result = 0
if err := client.Do(ctx, radix.FlatCmd(&result, "DEL", data.key)); err != nil {
log.WithError(err).Error("error code: 1061.3")
}
if result == 0 {
err := errors.New("failed to delete recovery key from redis")
log.WithError(err).Error("error code: 1061.4")
}
// update verification status in database
db := database.GetDB()
auth := model.Auth{}
// is data.value an email or hash of an email
isEmail := false
if lib.ValidateEmail(data.value) {
isEmail = true
}
if isEmail {
if err := db.Where("email = ?", data.value).First(&auth).Error; err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1061.5")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// email was in redis but not in relational db => missing data
log.WithError(err).Error("error code: 1061.6")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
if !isEmail {
if err := db.Where("email_hash = ?", data.value).First(&auth).Error; err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1061.7")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// email hash was in redis but not in relational db => missing data
log.WithError(err).Error("error code: 1061.8")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
if auth.VerifyEmail == model.EmailVerified {
httpResponse.Message = "email already verified"
httpStatusCode = http.StatusOK
return
}
auth.VerifyEmail = model.EmailVerified
auth.UpdatedAt = time.Now()
tx := db.Begin()
if err := tx.Save(&auth).Error; err != nil {
tx.Rollback()
log.WithError(err).Error("error code: 1061.9")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
tx.Commit()
httpResponse.Message = "email successfully verified"
httpStatusCode = http.StatusOK
return
}
// CreateVerificationEmail handles jobs for controller.CreateVerificationEmail
func CreateVerificationEmail(payload model.AuthPayload) (httpResponse model.HTTPResponse, httpStatusCode int) {
payload.Email = strings.TrimSpace(payload.Email)
if !lib.ValidateEmail(payload.Email) {
httpResponse.Message = "wrong email address"
httpStatusCode = http.StatusBadRequest
return
}
v, err := service.GetUserByEmail(payload.Email, true)
if err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1062.1")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
httpResponse.Message = "user not found"
httpStatusCode = http.StatusNotFound
return
}
// is email already verified
if v.VerifyEmail == model.EmailVerified {
httpResponse.Message = "email already verified"
httpStatusCode = http.StatusOK
return
}
// verify password
verifyPass, err := argon2.ComparePasswordAndHash(payload.Password, config.GetConfig().Security.HashSec, v.Password)
if err != nil {
log.WithError(err).Error("error code: 1062.2")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
if !verifyPass {
httpResponse.Message = "wrong credentials"
httpStatusCode = http.StatusBadRequest
return
}
// issue new verification code
emailDelivered, err := service.SendEmail(v.Email, model.EmailTypeVerifyEmailNewAcc)
if err != nil {
log.WithError(err).Error("error code: 1062.3")
httpResponse.Message = "email delivery service failed"
httpStatusCode = http.StatusInternalServerError
return
}
if !emailDelivered {
httpResponse.Message = "failed to send verification email"
httpStatusCode = http.StatusServiceUnavailable
return
}
httpResponse.Message = "sent verification email"
httpStatusCode = http.StatusOK
return
}
// VerifyUpdatedEmail receives tasks from controller.VerifyUpdatedEmail
//
// - verify newly added email address
//
// - update user email address
//
// - delete temporary data from database after verification process is done
func VerifyUpdatedEmail(payload model.AuthPayload) (httpResponse model.HTTPResponse, httpStatusCode int) {
payload.VerificationCode = strings.TrimSpace(payload.VerificationCode)
if payload.VerificationCode == "" {
httpResponse.Message = "required a valid email verification code"
httpStatusCode = http.StatusBadRequest
return
}
data := struct {
key string
value string
}{}
data.key = model.EmailUpdateKeyPrefix + payload.VerificationCode
// get redis client
client := *database.GetRedis()
rConnTTL := config.GetConfig().Database.REDIS.Conn.ConnTTL
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(rConnTTL)*time.Second)
defer cancel()
// is key available in redis
result := 0
if err := client.Do(ctx, radix.FlatCmd(&result, "EXISTS", data.key)); err != nil {
log.WithError(err).Error("error code: 1063.1")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
if result == 0 {
httpResponse.Message = "wrong/expired verification code"
httpStatusCode = http.StatusBadRequest
return
}
// find key in redis
if err := client.Do(ctx, radix.FlatCmd(&data.value, "GET", data.key)); err != nil {
log.WithError(err).Error("error code: 1063.2")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// delete key from redis
result = 0
if err := client.Do(ctx, radix.FlatCmd(&result, "DEL", data.key)); err != nil {
log.WithError(err).Error("error code: 1063.3")
}
if result == 0 {
err := errors.New("failed to delete recovery key from redis")
log.WithError(err).Error("error code: 1063.4")
}
// update user email in database
db := database.GetDB()
auth := model.Auth{}
tempEmail := model.TempEmail{}
// is data.value an email or hash of an email
isEmail := false
if lib.ValidateEmail(data.value) {
isEmail = true
}
if isEmail {
// check 'temp_emails' with the email in plaintext
if err := db.Where("email = ?", data.value).First(&tempEmail).Error; err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1063.5")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// data was in redis but not in relational db
// most probably using another verification code, the email was updated
// hence, expire this request
httpResponse.Message = "wrong/expired verification code"
httpStatusCode = http.StatusBadRequest
return
}
}
if !isEmail {
// check 'temp_emails' with hash of the email
if err := db.Where("email_hash = ?", data.value).First(&tempEmail).Error; err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1063.6")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// data was in redis but not in relational db
// most probably using another verification code, the email was updated
// hence, expire this request
httpResponse.Message = "wrong/expired verification code"
httpStatusCode = http.StatusBadRequest
return
}
}
// check 'auths'
// verify that this email is not used by another user
if isEmail {
err := db.Where("email = ?", tempEmail.Email).First(&auth).Error
if err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1063.71")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
if err == nil {
httpResponse.Message = "email already in use"
httpStatusCode = http.StatusBadRequest
return
}
}
if !isEmail {
err := db.Where("email_hash = ?", tempEmail.EmailHash).First(&auth).Error
if err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1063.72")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
if err == nil {
httpResponse.Message = "email already in use"
httpStatusCode = http.StatusBadRequest
return
}
}
// fetch auth data
if err := db.Where("auth_id = ?", tempEmail.IDAuth).First(&auth).Error; err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1063.73")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
// auth_id mismatch!
httpResponse.Message = "wrong/expired verification code"
httpStatusCode = http.StatusBadRequest
return
}
// update model
timeNow := time.Now()
auth.UpdatedAt = timeNow
auth.Email = tempEmail.Email
auth.EmailCipher = tempEmail.EmailCipher
auth.EmailNonce = tempEmail.EmailNonce
auth.EmailHash = tempEmail.EmailHash
// delete data from 'temp_emails'
tx := db.Begin()
if err := tx.Delete(&tempEmail).Error; err != nil {
tx.Rollback()
log.WithError(err).Error("error code: 1063.8")
} else {
tx.Commit()
}
// update data in 'auths'
tx = db.Begin()
if err := tx.Save(&auth).Error; err != nil {
tx.Rollback()
log.WithError(err).Error("error code: 1063.9")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
tx.Commit()
httpResponse.Message = "email address updated"
httpStatusCode = http.StatusOK
return
}
// GetUnverifiedEmail receives tasks from controller.GetUnverifiedEmail
//
// It retrieves unverified email information for a given user.
func GetUnverifiedEmail(claims middleware.MyCustomClaims) (httpResponse model.HTTPResponse, httpStatusCode int) {
// check auth validity
ok := service.ValidateAuthID(claims.AuthID)
if !ok {
httpResponse.Message = "access denied"
httpStatusCode = http.StatusUnauthorized
return
}
// read DB
db := database.GetDB()
tempEmail := model.TempEmail{}
// check 'temp_emails'
err := db.Where("id_auth = ?", claims.AuthID).First(&tempEmail).Error
if err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1064.1")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
httpResponse.Message = "no pending request"
}
// verification is pending to modify current email
if err == nil {
// decipher
if tempEmail.Email == "" {
if !config.IsCipher() {
e := errors.New("check env: ACTIVATE_CIPHER")
log.WithError(e).Error("error code: 1064.2")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
tempEmail.Email, err = service.DecryptEmail(tempEmail.EmailNonce, tempEmail.EmailCipher)
if err != nil {
log.WithError(err).Error("error code: 1064.3")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
// clear cipher data
tempEmail.EmailCipher = ""
tempEmail.EmailNonce = ""
tempEmail.EmailHash = ""
httpResponse.Message = tempEmail
}
httpStatusCode = http.StatusOK
return
}
// ResendVerificationCodeToModifyActiveEmail receives tasks from controller.ResendVerificationCodeToModifyActiveEmail
func ResendVerificationCodeToModifyActiveEmail(claims middleware.MyCustomClaims) (httpResponse model.HTTPResponse, httpStatusCode int) {
// check auth validity
ok := service.ValidateAuthID(claims.AuthID)
if !ok {
httpResponse.Message = "access denied"
httpStatusCode = http.StatusUnauthorized
return
}
// read DB
db := database.GetDB()
tempEmail := model.TempEmail{}
// check 'temp_emails'
err := db.Where("id_auth = ?", claims.AuthID).First(&tempEmail).Error
if err != nil {
if err.Error() != database.RecordNotFound {
// db read error
log.WithError(err).Error("error code: 1065.1")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
httpResponse.Message = "no pending request"
httpStatusCode = http.StatusBadRequest
return
}
// verification is pending to modify current email
// decipher
if tempEmail.Email == "" {
if !config.IsCipher() {
e := errors.New("check env: ACTIVATE_CIPHER")
log.WithError(e).Error("error code: 1065.2")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
tempEmail.Email, err = service.DecryptEmail(tempEmail.EmailNonce, tempEmail.EmailCipher)
if err != nil {
log.WithError(err).Error("error code: 1065.3")
httpResponse.Message = "internal server error"
httpStatusCode = http.StatusInternalServerError
return
}
}
// issue new verification code
emailDelivered, err := service.SendEmail(tempEmail.Email, model.EmailTypeVerifyUpdatedEmail)
if err != nil {
log.WithError(err).Error("error code: 1065.4")
httpResponse.Message = "email delivery service failed"
httpStatusCode = http.StatusInternalServerError
return
}
if !emailDelivered {
httpResponse.Message = "failed to send verification email"
httpStatusCode = http.StatusServiceUnavailable
return
}
httpResponse.Message = "sent verification email"
httpStatusCode = http.StatusOK
return
}