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
537
538
539
|
package user
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"html"
"net/http"
"time"
auth "donetick.com/core/internal/authorization"
cModel "donetick.com/core/internal/circle/model"
cRepo "donetick.com/core/internal/circle/repo"
"donetick.com/core/internal/email"
uModel "donetick.com/core/internal/user/model"
uRepo "donetick.com/core/internal/user/repo"
"donetick.com/core/internal/utils"
"donetick.com/core/logging"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
limiter "github.com/ulule/limiter/v3"
"google.golang.org/api/googleapi"
"google.golang.org/api/oauth2/v1"
)
type Handler struct {
userRepo *uRepo.UserRepository
circleRepo *cRepo.CircleRepository
jwtAuth *jwt.GinJWTMiddleware
email *email.EmailSender
}
func NewHandler(ur *uRepo.UserRepository, cr *cRepo.CircleRepository, jwtAuth *jwt.GinJWTMiddleware, email *email.EmailSender) *Handler {
return &Handler{
userRepo: ur,
circleRepo: cr,
jwtAuth: jwtAuth,
email: email,
}
}
func (h *Handler) GetAllUsers() gin.HandlerFunc {
return func(c *gin.Context) {
currentUser, ok := auth.CurrentUser(c)
if !ok {
c.JSON(500, gin.H{
"error": "Error getting current user",
})
return
}
users, err := h.userRepo.GetAllUsers(c, currentUser.CircleID)
if err != nil {
c.JSON(500, gin.H{
"error": "Error getting users",
})
return
}
c.JSON(200, gin.H{
"res": users,
})
}
}
func (h *Handler) signUp(c *gin.Context) {
type SignUpReq struct {
Username string `json:"username" binding:"required,min=4,max=20"`
Password string `json:"password" binding:"required,min=8,max=45"`
Email string `json:"email" binding:"required,email"`
DisplayName string `json:"displayName"`
}
var signupReq SignUpReq
if err := c.BindJSON(&signupReq); err != nil {
c.JSON(400, gin.H{
"error": "Invalid request",
})
return
}
if signupReq.DisplayName == "" {
signupReq.DisplayName = signupReq.Username
}
password, err := auth.EncodePassword(signupReq.Password)
signupReq.Username = html.EscapeString(signupReq.Username)
signupReq.DisplayName = html.EscapeString(signupReq.DisplayName)
if err != nil {
c.JSON(500, gin.H{
"error": "Error encoding password",
})
return
}
var insertedUser *uModel.User
if insertedUser, err = h.userRepo.CreateUser(c, &uModel.User{
Username: signupReq.Username,
Password: password,
DisplayName: signupReq.DisplayName,
Email: signupReq.Email,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}); err != nil {
c.JSON(500, gin.H{
"error": "Error creating user, email already exists or username is taken",
})
return
}
// var userCircle *circle.Circle
// var userRole string
userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{
Name: signupReq.DisplayName + "'s circle",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
InviteCode: utils.GenerateInviteCode(c),
})
if err != nil {
c.JSON(500, gin.H{
"error": "Error creating circle",
})
return
}
if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
UserID: insertedUser.ID,
CircleID: userCircle.ID,
Role: "admin",
IsActive: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}); err != nil {
c.JSON(500, gin.H{
"error": "Error adding user to circle",
})
return
}
insertedUser.CircleID = userCircle.ID
if err := h.userRepo.UpdateUser(c, insertedUser); err != nil {
c.JSON(500, gin.H{
"error": "Error updating user",
})
return
}
c.JSON(201, gin.H{})
}
func (h *Handler) GetUserProfile(c *gin.Context) {
user, ok := auth.CurrentUser(c)
if !ok {
c.JSON(500, gin.H{
"error": "Error getting user",
})
return
}
c.JSON(200, gin.H{
"res": user,
})
}
func (h *Handler) thirdPartyAuthCallback(c *gin.Context) {
// read :provider from path param, if param is google check the token with google if it's valid and fetch the user details:
logger := logging.FromContext(c)
provider := c.Param("provider")
logger.Infow("account.handler.thirdPartyAuthCallback", "provider", provider)
if provider == "google" {
c.Set("auth_provider", "3rdPartyAuth")
type OAuthRequest struct {
Token string `json:"token" binding:"required"`
Provider string `json:"provider" binding:"required"`
}
var body OAuthRequest
if err := c.ShouldBindJSON(&body); err != nil {
logger.Errorw("account.handler.thirdPartyAuthCallback failed to bind", "err", err)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid request",
})
return
}
// logger.Infow("account.handler.thirdPartyAuthCallback", "token", token)
service, err := oauth2.New(http.DefaultClient)
// tokenInfo, err := service.Tokeninfo().AccessToken(token).Do()
userinfo, err := service.Userinfo.Get().Do(googleapi.QueryParameter("access_token", body.Token))
logger.Infow("account.handler.thirdPartyAuthCallback", "tokenInfo", userinfo)
if err != nil {
logger.Errorw("account.handler.thirdPartyAuthCallback failed to get token info", "err", err)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid token",
})
return
}
acc, err := h.userRepo.FindByEmail(c, userinfo.Email)
if err != nil {
// create a random password for the user using crypto/rand:
password := auth.GenerateRandomPassword(12)
encodedPassword, err := auth.EncodePassword(password)
acc = &uModel.User{
Username: userinfo.Id,
Email: userinfo.Email,
Image: userinfo.Picture,
Password: encodedPassword,
DisplayName: userinfo.GivenName,
Provider: 2,
}
createdUser, err := h.userRepo.CreateUser(c, acc)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to create user",
})
return
}
// Create Circle for the user:
userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{
Name: userinfo.GivenName + "'s circle",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
InviteCode: utils.GenerateInviteCode(c),
})
if err != nil {
c.JSON(500, gin.H{
"error": "Error creating circle",
})
return
}
if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{
UserID: createdUser.ID,
CircleID: userCircle.ID,
Role: "admin",
IsActive: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}); err != nil {
c.JSON(500, gin.H{
"error": "Error adding user to circle",
})
return
}
createdUser.CircleID = userCircle.ID
if err := h.userRepo.UpdateUser(c, createdUser); err != nil {
c.JSON(500, gin.H{
"error": "Error updating user",
})
return
}
}
// use auth to generate a token for the user:
c.Set("user_account", acc)
h.jwtAuth.Authenticator(c)
tokenString, expire, err := h.jwtAuth.TokenGenerator(acc)
if err != nil {
logger.Errorw("Unable to Generate a Token")
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to Generate a Token",
})
return
}
c.JSON(http.StatusOK, gin.H{"token": tokenString, "expire": expire})
return
}
}
func (h *Handler) resetPassword(c *gin.Context) {
log := logging.FromContext(c)
type ResetPasswordReq struct {
Email string `json:"email" binding:"required,email"`
}
var req ResetPasswordReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid request",
})
return
}
user, err := h.userRepo.FindByEmail(c, req.Email)
if err != nil {
c.JSON(http.StatusOK, gin.H{})
log.Error("account.handler.resetPassword failed to find user")
return
}
if user.Provider != 0 {
// user create account thought login with Gmail. they can reset the password they just need to login with google again
c.JSON(
http.StatusForbidden,
gin.H{
"error": "User account created with google login. Please login with google",
},
)
return
}
// generate a random password:
token, err := auth.GenerateEmailResetToken(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to generate token",
})
return
}
err = h.userRepo.SetPasswordResetToken(c, req.Email, token)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to generate password",
})
return
}
// send an email to the user with the new password:
err = h.email.SendResetPasswordEmail(c, req.Email, token)
if err != nil {
log.Errorw("account.handler.resetPassword failed to send email", "err", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to send email",
})
return
}
// send an email to the user with the new password:
c.JSON(http.StatusOK, gin.H{})
}
func (h *Handler) updateUserPassword(c *gin.Context) {
logger := logging.FromContext(c)
// read the code from query param:
code := c.Query("c")
email, code, err := email.DecodeEmailAndCode(code)
if err != nil {
logger.Errorw("account.handler.verify failed to decode email and code", "err", err)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid code",
})
return
}
// read password from body:
type RequestBody struct {
Password string `json:"password" binding:"required,min=8,max=32"`
}
var body RequestBody
if err := c.ShouldBindJSON(&body); err != nil {
logger.Errorw("user.handler.resetAccountPassword failed to bind", "err", err)
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid request",
})
return
}
password, err := auth.EncodePassword(body.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to process password",
})
return
}
err = h.userRepo.UpdatePasswordByToken(c.Request.Context(), email, code, password)
if err != nil {
logger.Errorw("account.handler.resetAccountPassword failed to reset password", "err", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Unable to reset password",
})
return
}
c.JSON(http.StatusOK, gin.H{})
}
func (h *Handler) UpdateUserDetails(c *gin.Context) {
type UpdateUserReq struct {
DisplayName *string `json:"displayName" binding:"omitempty"`
ChatID *int64 `json:"chatID" binding:"omitempty"`
Image *string `json:"image" binding:"omitempty"`
}
user, ok := auth.CurrentUser(c)
if !ok {
c.JSON(500, gin.H{
"error": "Error getting user",
})
return
}
var req UpdateUserReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"error": "Invalid request",
})
return
}
// update non-nil fields:
if req.DisplayName != nil {
user.DisplayName = *req.DisplayName
}
if req.ChatID != nil {
user.ChatID = *req.ChatID
}
if req.Image != nil {
user.Image = *req.Image
}
if err := h.userRepo.UpdateUser(c, user); err != nil {
c.JSON(500, gin.H{
"error": "Error updating user",
})
return
}
c.JSON(200, user)
}
func (h *Handler) CreateLongLivedToken(c *gin.Context) {
currentUser, ok := auth.CurrentUser(c)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
return
}
type TokenRequest struct {
Name string `json:"name" binding:"required"`
}
var req TokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
// Step 1: Generate a secure random number
randomBytes := make([]byte, 16) // 128 bits are enough for strong randomness
_, err := rand.Read(randomBytes)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate random part of the token"})
return
}
timestamp := time.Now().Unix()
hashInput := fmt.Sprintf("%s:%d:%x", currentUser.Username, timestamp, randomBytes)
hash := sha256.Sum256([]byte(hashInput))
token := hex.EncodeToString(hash[:])
tokenModel, err := h.userRepo.StoreAPIToken(c, currentUser.ID, req.Name, token)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store the token"})
return
}
c.JSON(http.StatusOK, gin.H{"res": tokenModel})
}
func (h *Handler) GetAllUserToken(c *gin.Context) {
currentUser, ok := auth.CurrentUser(c)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
return
}
tokens, err := h.userRepo.GetAllUserTokens(c, currentUser.ID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user tokens"})
return
}
c.JSON(http.StatusOK, gin.H{"res": tokens})
}
func (h *Handler) DeleteUserToken(c *gin.Context) {
currentUser, ok := auth.CurrentUser(c)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
return
}
tokenID := c.Param("id")
err := h.userRepo.DeleteAPIToken(c, currentUser.ID, tokenID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete the token"})
return
}
c.JSON(http.StatusOK, gin.H{})
}
func (h *Handler) UpdateNotificationTarget(c *gin.Context) {
currentUser, ok := auth.CurrentUser(c)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"})
return
}
type Request struct {
Type uModel.UserNotificationType `json:"type" binding:"required"`
Token string `json:"token" binding:"required"`
}
var req Request
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
err := h.userRepo.UpdateNotificationTarget(c, currentUser.ID, req.Token, req.Type)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update notification target"})
return
}
c.JSON(http.StatusOK, gin.H{})
}
func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware, limiter *limiter.Limiter) {
userRoutes := router.Group("users")
userRoutes.Use(auth.MiddlewareFunc(), utils.RateLimitMiddleware(limiter))
{
userRoutes.GET("/", h.GetAllUsers())
userRoutes.GET("/profile", h.GetUserProfile)
userRoutes.PUT("", h.UpdateUserDetails)
userRoutes.POST("/tokens", h.CreateLongLivedToken)
userRoutes.GET("/tokens", h.GetAllUserToken)
userRoutes.DELETE("/tokens/:id", h.DeleteUserToken)
userRoutes.PUT("/targets", h.UpdateNotificationTarget)
}
authRoutes := router.Group("auth")
authRoutes.Use(utils.RateLimitMiddleware(limiter))
{
authRoutes.POST("/", h.signUp)
authRoutes.POST("login", auth.LoginHandler)
authRoutes.GET("refresh", auth.RefreshHandler)
authRoutes.POST("/:provider/callback", h.thirdPartyAuthCallback)
authRoutes.POST("reset", h.resetPassword)
authRoutes.POST("password", h.updateUserPassword)
}
}
|