/
account.go
502 lines (419 loc) · 15.8 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
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
package controllers
import (
"fmt"
"net/http"
"net/mail"
"net/url"
"time"
log "github.com/Sirupsen/logrus"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"twreporter.org/go-api/globals"
"twreporter.org/go-api/models"
"twreporter.org/go-api/utils"
)
const (
// TODO: Update later after UX designed
authErrorPage = "https://www.twreporter.org/"
defaultRedirectPage = "https://www.twreporter.org/"
idTokenExpiration = 60 * 60 * 24 * 30 * 6
)
var defaultPath = "/"
// SignIn - send email containing sign-in information to the client
func (mc *MembershipController) SignIn(c *gin.Context) (int, gin.H, error) {
// SignInBody is to store POST body
type SignInBody struct {
Email string `json:"email" form:"email" binding:"required"`
Destination string `json:"destination" form:"destination"`
}
const errorWhere = "MembershipController.SignIn"
const SignInMailSubject = "登入報導者"
const activateHost = "www.twreporter.org"
var activeToken string
var appErr *models.AppError
var email string
var err error
var matchedUser models.User
var ra models.ReporterAccount
var signIn SignInBody
var statusCode int
// extract email and password field in POST body
if err = c.Bind(&signIn); err != nil {
return http.StatusBadRequest, gin.H{"status": "fail", "data": SignInBody{
Email: "email is required",
Destination: "destination is optional",
}}, nil
}
email = signIn.Email
// Check if mail address is not malform
_, err = mail.ParseAddress(email)
if err != nil {
return http.StatusBadRequest, gin.H{"status": "fail", "data": SignInBody{
Email: "email is malform",
}}, nil
}
// generate active token
activeToken, err = utils.GenerateRandomString(8)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Generating active token occurs error", err.Error(), http.StatusInternalServerError)
}
// get reporter account by email from reporter_account table
ra, err = mc.Storage.GetReporterAccountData(email)
// account is already signed in before
if err == nil {
// update active token and token expire time
ra.ActivateToken = activeToken
ra.ActExpTime = time.Now().Add(time.Duration(15) * time.Minute)
if err = mc.Storage.UpdateReporterAccount(ra); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Updating DB occurs error", err.Error(), http.StatusInternalServerError)
}
statusCode = http.StatusOK
} else {
// account is not signed in before
appErr = err.(*models.AppError)
// internal server error
if appErr.StatusCode != http.StatusNotFound {
return 0, gin.H{}, appErr
}
ra = models.ReporterAccount{
Email: email,
ActivateToken: activeToken,
// expire time is one day
ActExpTime: time.Now().Add(time.Duration(15) * time.Minute),
}
// try to find record by email in users table
matchedUser, err = mc.Storage.GetUserByEmail(email)
// the user record is not existed
if err != nil {
// create records both in reporter_accounts and users table
_, err = mc.Storage.InsertUserByReporterAccount(ra)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Inserting new record into DB occurs error", err.Error(), http.StatusInternalServerError)
}
} else {
// if user existed,
// create a record in reporter_accounts table
// and connect these two records
ra.UserID = matchedUser.ID
err = mc.Storage.InsertReporterAccount(ra)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Inserting new record into DB occurs error", err.Error(), http.StatusInternalServerError)
}
}
statusCode = http.StatusCreated
}
// send activation email
err = postMailServiceEndpoint(activationReqBody{
Email: email,
ActivateLink: fmt.Sprintf("%s://%s:%s/activate?email=%s&token=%s&destination=%s",
globals.Conf.App.Protocol, activateHost, globals.Conf.App.Port, email, activeToken, signIn.Destination),
}, fmt.Sprintf("http://localhost:%s/v1/%s", globals.LocalhostPort, globals.SendActivationRoutePath))
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Sending activation email occurs error", err.Error(), http.StatusInternalServerError)
}
return statusCode, gin.H{"status": "success", "data": SignInBody{
Email: email,
Destination: signIn.Destination,
}}, nil
}
// Activate - validate the reporter account
// if validated, then sign in successfully,
// otherwise, sign in unsuccessfully.
func (mc *MembershipController) Activate(c *gin.Context) (int, gin.H, error) {
const errorWhere = "MembershipController.Activate"
var appErr *models.AppError
var err error
var jwt string
var ra models.ReporterAccount
var user models.User
email := c.Query("email")
token := c.Query("token")
// get reporter account by email from reporter_account table
if ra, err = mc.Storage.GetReporterAccountData(email); err != nil {
appErr = err.(*models.AppError)
return 0, gin.H{}, models.NewAppError(errorWhere, fmt.Sprintf("Activating email %s occurs error", email), err.Error(), appErr.StatusCode)
}
// check expire time
if ra.ActExpTime.Sub(time.Now()) < time.Duration(0) {
return 0, gin.H{}, models.NewAppError(errorWhere, "ActivateToken is expired", "", http.StatusUnauthorized)
}
// check token
if ra.ActivateToken == token {
// set active expire time to now
// which make sure the same token not be signed in again
ra.ActExpTime = time.Now()
// handle internal server error - can't update the record in reporter_account table
if err = mc.Storage.UpdateReporterAccount(ra); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Updating reporter_account occurs error", err.Error(), http.StatusInternalServerError)
}
// handle internal server error - can't query the record from users table
if user, err = mc.Storage.GetUserDataByReporterAccount(ra); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Querying reporter_account occurs error", err.Error(), http.StatusInternalServerError)
}
// handle internal server error - cannot generate JWT
if jwt, err = utils.RetrieveV1Token(user.ID, user.Email.String); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Generating JWT occurs error", err.Error(), http.StatusInternalServerError)
}
return 200, gin.H{"status": "success",
"id": user.ID, "privilege": user.Privilege, "firstname": user.FirstName.String,
"lastname": user.LastName.String, "email": user.Email.String, "jwt": jwt}, nil
}
return 0, gin.H{}, models.NewAppError(errorWhere, "Token is invalid", "", http.StatusUnauthorized)
}
// RenewJWT - validate the old JWT,
// if validated, then renew a new one
func (mc *MembershipController) RenewJWT(c *gin.Context) (int, gin.H, error) {
const errorWhere = "MembershipController.RenewJWT"
var appErr *models.AppError
var err error
var jwt string
var user models.User
userID := c.Param("userID")
if user, err = mc.Storage.GetUserByID(userID); err != nil {
appErr = err.(*models.AppError)
return 0, gin.H{}, models.NewAppError(errorWhere, "Renewing JWT occurs error", appErr.Error(), appErr.StatusCode)
}
if jwt, err = utils.RetrieveV1Token(user.ID, user.Email.String); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Generating JWT occurs error", err.Error(), http.StatusInternalServerError)
}
return http.StatusOK, gin.H{"status": "success", "data": struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
}{
Token: jwt,
TokenType: "Bearer",
}}, nil
}
// SignInV2 - send email containing sign-in information to the client
func (mc *MembershipController) SignInV2(c *gin.Context) (int, gin.H, error) {
// SignInBody is to store POST body
type SignInBody struct {
Email string `json:"email" form:"email" binding:"required"`
Destination string `json:"destination" form:"destination"`
}
const errorWhere = "MembershipController.SignInV2"
const SignInMailSubject = "登入報導者"
var activateHost string
var activeToken string
var appErr *models.AppError
var email string
var err error
var matchedUser models.User
var ra models.ReporterAccount
var signIn SignInBody
var statusCode int
switch globals.Conf.Environment {
case "development":
activateHost = "localhost"
case "staging":
activateHost = "staging-go-api.twreporter.org"
case "production":
activateHost = "go-api.twreporter.org"
default:
activateHost = "localhost"
}
// extract email and password field in POST body
if err = c.Bind(&signIn); err != nil {
return http.StatusBadRequest, gin.H{"status": "fail", "data": SignInBody{
Email: "email is required",
Destination: "destination is optional",
}}, nil
}
email = signIn.Email
// Check if mail address is not malform
_, err = mail.ParseAddress(email)
if err != nil {
return http.StatusBadRequest, gin.H{"status": "fail", "data": SignInBody{
Email: "email is malform",
}}, nil
}
// generate active token
activeToken, err = utils.GenerateRandomString(8)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Generating active token occurs error", err.Error(), http.StatusInternalServerError)
}
// get reporter account by email from reporter_account table
ra, err = mc.Storage.GetReporterAccountData(email)
// account is already signed in before
if err == nil {
// update active token and token expire time
ra.ActivateToken = activeToken
ra.ActExpTime = time.Now().Add(time.Duration(15) * time.Minute)
if err = mc.Storage.UpdateReporterAccount(ra); err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Updating DB occurs error", err.Error(), http.StatusInternalServerError)
}
statusCode = http.StatusOK
} else {
// account is not signed in before
appErr = err.(*models.AppError)
// internal server error
if appErr.StatusCode != http.StatusNotFound {
return 0, gin.H{}, appErr
}
ra = models.ReporterAccount{
Email: email,
ActivateToken: activeToken,
// expire time is one day
ActExpTime: time.Now().Add(time.Duration(15) * time.Minute),
}
// try to find record by email in users table
matchedUser, err = mc.Storage.GetUserByEmail(email)
// the user record is not existed
if err != nil {
// create records both in reporter_accounts and users table
_, err = mc.Storage.InsertUserByReporterAccount(ra)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Inserting new record into DB occurs error", err.Error(), http.StatusInternalServerError)
}
} else {
// if user existed,
// create a record in reporter_accounts table
// and connect these two records
ra.UserID = matchedUser.ID
err = mc.Storage.InsertReporterAccount(ra)
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Inserting new record into DB occurs error", err.Error(), http.StatusInternalServerError)
}
}
statusCode = http.StatusCreated
}
// send activation email
err = postMailServiceEndpoint(activationReqBody{
Email: email,
ActivateLink: fmt.Sprintf("%s://%s:%s/v2/auth/activate?email=%s&token=%s&destination=%s",
globals.Conf.App.Protocol,
activateHost,
globals.Conf.App.Port,
url.QueryEscape(email),
url.QueryEscape(activeToken),
url.QueryEscape(signIn.Destination),
),
}, fmt.Sprintf("http://localhost:%s/v1/%s", globals.LocalhostPort, globals.SendActivationRoutePath))
if err != nil {
return 0, gin.H{}, models.NewAppError(errorWhere, "Sending activation email occurs error", err.Error(), http.StatusInternalServerError)
}
return statusCode, gin.H{"status": "success", "data": SignInBody{
Email: email,
Destination: signIn.Destination,
}}, nil
}
// ActivateV2 - validate the reporter account
// if validated, then sign in successfully,
// otherwise, sign in unsuccessfully.
func (mc *MembershipController) ActivateV2(c *gin.Context) {
const errorWhere = "MembershipController.ActivateV2"
var defaultDomain = globals.Conf.App.Domain
var err error
var ra models.ReporterAccount
var user models.User
email := c.Query("email")
token := c.Query("token")
destination := c.Query("destination")
// If destination is unavailable or invalid, redirect back to main site.
u, err := url.Parse(destination)
if nil != err {
destination = defaultRedirectPage
u, _ = url.Parse(destination)
}
// Error clean up
defer func() {
if nil != err {
appErr := err.(*models.AppError)
log.Error(appErr.Error())
//Always redirect to a designated page
c.Redirect(http.StatusTemporaryRedirect, authErrorPage)
}
}()
// get reporter account by email from reporter_account table
if ra, err = mc.Storage.GetReporterAccountData(email); err != nil {
return
}
// check expire time
if ra.ActExpTime.Sub(time.Now()) < time.Duration(0) {
err = models.NewAppError(errorWhere, "", "ActivateToken is expired", http.StatusUnauthorized)
return
}
// validate token
if ra.ActivateToken != token {
err = models.NewAppError(errorWhere, "", "Token is invalid", http.StatusUnauthorized)
return
}
// set active expire time to now to ensure the same token only being used once
ra.ActExpTime = time.Now()
// Error occurs during updating the record in reporter_account table
if err = mc.Storage.UpdateReporterAccount(ra); err != nil {
return
}
// Error occurs during querying the record from users table
if user, err = mc.Storage.GetUserDataByReporterAccount(ra); err != nil {
return
}
// Create id token for jwt endpoint retrival
idToken, err := utils.RetrieveV2IDToken(user.ID, user.Email.ValueOrZero(), user.FirstName.ValueOrZero(), user.LastName.ValueOrZero(), idTokenExpiration)
if nil != err {
log.Error(errorWhere + "(): " + err.Error())
idToken = "twreporter-id-token"
}
// Setup Set-Cookie header in response header
// Determine cookie property
secure := false
if "https" == u.Scheme {
secure = true
}
c.SetCookie("id_token", idToken, idTokenExpiration, defaultPath, defaultDomain, secure, true)
c.Redirect(http.StatusTemporaryRedirect, destination)
}
// TokenDispatch returns the `access_token` in payload for frontend server
func (mc *MembershipController) TokenDispatch(c *gin.Context) {
const acccessTokenExpiration = 60 * 60 * 24 * 14 // 2week
const idTokenKey = "id_token"
var accessToken string
var claims = new(utils.IDTokenJWTClaims)
var err error
var idToken string
var user models.User
if idToken, err = c.Cookie(idTokenKey); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "fail", "data": gin.H{"req.Headers.Cookies.id_token": err.Error()}})
return
}
if _, _, err = new(jwt.Parser).ParseUnverified(idToken, claims); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "fail", "data": gin.H{"req.Headers.Cookies.id_token": err.Error()}})
return
}
user, err = mc.Storage.GetUserByID(fmt.Sprint(claims.UserID))
if nil != err {
appErr := err.(*models.AppError)
log.Error(appErr.Error())
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "cannot get user data"})
return
}
accessToken, err = utils.RetrieveV2AccessToken(user.ID, user.Email.ValueOrZero(), acccessTokenExpiration)
if err != nil {
appErr := err.(*models.AppError)
log.Error(appErr.Error())
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "Error occurs during generating access_token JWT"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "data": gin.H{
"jwt": accessToken,
}})
}
// TokenInvalidate deletes the id_token stored in the client side
func (mc *MembershipController) TokenInvalidate(c *gin.Context) {
const signInPage = "https://accounts.twreporter.org/signin"
var defaultDomain = globals.Conf.App.Domain
cookieName := "id_token"
invalidateExp := -1
destination := c.Query("destination")
if destination == "" {
destination = signInPage
}
// If destination is unavailable or invalid, redirect back to signin page
u, err := url.Parse(destination)
if nil != err {
destination = signInPage
u, _ = url.Parse(destination)
}
c.SetCookie(cookieName, "", invalidateExp, defaultPath, defaultDomain, u.Scheme == "https", true)
c.Redirect(http.StatusTemporaryRedirect, destination)
}