forked from red-gold/telar-web
/
verification.go
384 lines (332 loc) · 13.5 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
package handlers
import (
"fmt"
"net/http"
"github.com/GMcD/telar-web/constants"
authConfig "github.com/GMcD/telar-web/micros/auth/config"
"github.com/GMcD/telar-web/micros/auth/database"
dto "github.com/GMcD/telar-web/micros/auth/dto"
models "github.com/GMcD/telar-web/micros/auth/models"
"github.com/GMcD/telar-web/micros/auth/provider"
service "github.com/GMcD/telar-web/micros/auth/services"
"github.com/gofiber/fiber/v2"
uuid "github.com/gofrs/uuid"
coreConfig "github.com/red-gold/telar-core/config"
"github.com/red-gold/telar-core/pkg/log"
"github.com/red-gold/telar-core/utils"
)
// Data for signup verify page template
type signupVerifyPageData struct {
title string
orgName string
orgAvatar string
appName string
actionForm string
baseRoutes string
token string
message string
}
// VerifySignupHandle verify signup token
func VerifySignupHandle(c *fiber.Ctx) error {
model := &models.VerifySignupModel{
Code: c.FormValue("code"),
Token: c.FormValue("verificaitonSecret"),
ResponseType: c.FormValue("responseType"),
}
if model.ResponseType == SPAResponseType {
return VerifySignupSPA(c, model)
}
return VerifySignupSSR(c, model)
}
func VerifySignupSPA(c *fiber.Ctx, model *models.VerifySignupModel) error {
// Validate token
remoteIpAddress := c.IP()
claims, errToken := utils.ValidateToken([]byte(*coreConfig.AppConfig.PublicKey), model.Token)
if errToken != nil {
log.Error("[VerifySignupSPA] Token validation: %s", errToken.Error())
return c.Status(http.StatusBadRequest).JSON(utils.Error("needValidToken", "Error happened in validating token!"))
}
claimMap, _ := claims["claim"].(map[string]interface{})
userRemoteIp, _ := claimMap["remoteIpAddress"].(string)
verifyType := claimMap["verifyType"].(string)
verifyMode, _ := claimMap["mode"].(string)
verifyId, _ := claimMap["verifyId"].(string)
userId, _ := claimMap["userId"].(string)
fullName, _ := claimMap["fullName"].(string)
email, _ := claimMap["email"].(string)
phoneNumber, _ := claimMap["phoneNumber"].(string)
password, _ := claimMap["password"].(string)
verifyTarget := ""
fmt.Printf("\nuserId: %s, fullName: %s, email: %s, password: %s, userRemoteIp: %s, verifyType: %v, verifyMode: %v, verifyId: %s\n",
userId, fullName, email, password, userRemoteIp, verifyType, verifyMode, verifyId)
emailVerified := false
phoneVerified := false
if verifyType == constants.EmailVerifyConst.String() {
verifyTarget = email
emailVerified = true
} else {
verifyTarget = phoneNumber
phoneVerified = true
}
if remoteIpAddress != userRemoteIp {
log.Error("[VerifySignupSPA] The request is from different remote ip address!")
return c.Status(http.StatusBadRequest).JSON(utils.Error("invalidToken", "Error happened in validating token!"))
}
// Create service
userAuthService, serviceErr := service.NewUserAuthService(database.Db)
if serviceErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal/userAuthService", serviceErr.Error()))
}
userVerificationService, serviceErr := service.NewUserVerificationService(database.Db)
if serviceErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal/userVerificationService", serviceErr.Error()))
}
userUUID, userUuidErr := uuid.FromString(userId)
if userUuidErr != nil {
return c.Status(http.StatusBadRequest).JSON(utils.Error("parseUserUUIDError", userUuidErr.Error()))
}
verifyUUID, verifyUuidErr := uuid.FromString(verifyId)
if verifyUuidErr != nil {
errorMessage := fmt.Sprintf("Can not parse verify id! error: %s", verifyUuidErr.Error())
log.Error(errorMessage)
return c.Status(http.StatusBadRequest).JSON(utils.Error("parseVerifyUUIDError", "Can not parse verify id!"))
}
verifyStatus, verifyErr := userVerificationService.VerifyUserByCode(userUUID, verifyUUID, remoteIpAddress, model.Code, verifyTarget)
if verifyErr != nil {
errorMessage := fmt.Sprintf("Cannot verify user by provided code! error: %s", verifyErr.Error())
log.Error(errorMessage)
return c.Status(http.StatusBadRequest).JSON(utils.Error("invalidCode", "Cannot verify user by provided code!"))
}
if !verifyStatus {
errorMessage := "The code is wrong!"
log.Error(errorMessage)
return c.Status(http.StatusBadRequest).JSON(utils.Error("wrongCode", "The code is wrong!"))
}
createdDate := utils.UTCNowUnix()
hashPassword, hashErr := utils.Hash(password)
if hashErr != nil {
errorMessage := fmt.Sprintf("Cannot hash the password! error: %s", hashErr.Error())
log.Error(errorMessage)
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal", "Error happened during verification!"))
}
newUserAuth := &dto.UserAuth{
ObjectId: userUUID,
Username: email,
Password: hashPassword,
AccessToken: model.Token,
EmailVerified: emailVerified,
Role: "user",
PhoneVerified: phoneVerified,
CreatedDate: createdDate,
LastUpdated: createdDate,
}
userAuthErr := userAuthService.SaveUserAuth(newUserAuth)
if userAuthErr != nil {
errorMessage := fmt.Sprintf("Cannot save user authentication! error: %s", userAuthErr.Error())
log.Error(errorMessage)
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal", "Error happened during verification!"))
}
socialName := generateSocialName(fullName, userId)
newUserProfile := &models.UserProfileModel{
ObjectId: userUUID,
FullName: fullName,
SocialName: socialName,
CreatedDate: createdDate,
LastUpdated: createdDate,
Email: email,
Avatar: "https://util.telar.dev/api/avatars/" + userUUID.String(),
Banner: fmt.Sprintf("https://picsum.photos/id/%d/900/300/?blur", generateRandomNumber(1, 1000)),
Permission: constants.Public,
}
userProfileErr := saveUserProfile(newUserProfile)
if userProfileErr != nil {
log.Error("Save user profile %s", userProfileErr.Error())
return c.Status(http.StatusInternalServerError).JSON(utils.Error("canNotSaveUserProfile", "Cannot save user profile!"))
}
setupErr := initUserSetup(newUserAuth.ObjectId, newUserAuth.Username, "", newUserProfile.FullName, newUserAuth.Role)
if setupErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("initUserSetupError", fmt.Sprintf("Cannot initialize user setup! error: %s", setupErr.Error())))
}
return c.SendStatus(http.StatusOK)
}
func VerifySignupSSR(c *fiber.Ctx, model *models.VerifySignupModel) error {
prettyURL := utils.GetPrettyURLf(authConfig.AuthConfig.BaseRoute)
signupVerifyData := &signupVerifyPageData{
title: "Login - Telar Social",
orgName: *coreConfig.AppConfig.OrgName,
orgAvatar: *coreConfig.AppConfig.OrgAvatar,
appName: *coreConfig.AppConfig.AppName,
actionForm: prettyURL + "/signup/verify",
token: model.Token,
message: "",
}
// Validate token
remoteIpAddress := c.IP()
claims, errToken := utils.ValidateToken([]byte(*coreConfig.AppConfig.PublicKey), model.Token)
if errToken != nil {
errorMessage := fmt.Sprintf("Can not parse token : %s",
errToken.Error())
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
claimMap, _ := claims["claim"].(map[string]interface{})
userRemoteIp, _ := claimMap["remoteIpAddress"].(string)
verifyType := claimMap["verifyType"].(string)
verifyMode, _ := claimMap["mode"].(string)
verifyId, _ := claimMap["verifyId"].(string)
userId, _ := claimMap["userId"].(string)
fullName, _ := claimMap["fullName"].(string)
email, _ := claimMap["email"].(string)
phoneNumber, _ := claimMap["phoneNumber"].(string)
password, _ := claimMap["password"].(string)
verifyTarget := ""
fmt.Printf("\nuserId: %s, fullName: %s, email: %s, password: %s, userRemoteIp: %s, verifyType: %v, verifyMode: %v, verifyId: %s\n",
userId, fullName, email, password, userRemoteIp, verifyType, verifyMode, verifyId)
emailVerified := false
phoneVerified := false
if verifyType == constants.EmailVerifyConst.String() {
verifyTarget = email
emailVerified = true
} else {
verifyTarget = phoneNumber
phoneVerified = true
}
if remoteIpAddress != userRemoteIp {
errorMessage := "The request is from different remote ip address!"
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
// Create service
userAuthService, serviceErr := service.NewUserAuthService(database.Db)
if serviceErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal/userAuthService", serviceErr.Error()))
}
userVerificationService, serviceErr := service.NewUserVerificationService(database.Db)
if serviceErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal/userVerificationService", serviceErr.Error()))
}
userUUID, userUuidErr := uuid.FromString(userId)
if userUuidErr != nil {
return c.Status(http.StatusBadRequest).JSON(utils.Error("parseUserUUIDError", userUuidErr.Error()))
}
verifyUUID, verifyUuidErr := uuid.FromString(verifyId)
if verifyUuidErr != nil {
return c.Status(http.StatusBadRequest).JSON(utils.Error("parseVerifyUUIDError", fmt.Sprintf("Can not parse verify id! error: %s", verifyUuidErr.Error())))
}
verifyStatus, verifyErr := userVerificationService.VerifyUserByCode(userUUID, verifyUUID, remoteIpAddress, model.Code, verifyTarget)
if verifyErr != nil {
errorMessage := fmt.Sprintf("Cannot verify user by provided code! error: %s", verifyErr.Error())
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
if !verifyStatus {
errorMessage := "The code is wrong!"
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
createdDate := utils.UTCNowUnix()
hashPassword, hashErr := utils.Hash(password)
if hashErr != nil {
errorMessage := fmt.Sprintf("Cannot hash the password! error: %s", hashErr.Error())
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
newUserAuth := &dto.UserAuth{
ObjectId: userUUID,
Username: email,
Password: hashPassword,
AccessToken: model.Token,
EmailVerified: emailVerified,
Role: "user",
PhoneVerified: phoneVerified,
CreatedDate: createdDate,
LastUpdated: createdDate,
}
userAuthErr := userAuthService.SaveUserAuth(newUserAuth)
if userAuthErr != nil {
errorMessage := fmt.Sprintf("Cannot save user authentication! error: %s", userAuthErr.Error())
signupVerifyData.message = errorMessage
return renderCodeVerify(c, signupVerifyData)
}
socialName := generateSocialName(fullName, userId)
newUserProfile := &models.UserProfileModel{
ObjectId: userUUID,
FullName: fullName,
SocialName: socialName,
CreatedDate: createdDate,
LastUpdated: createdDate,
Email: email,
Avatar: "https://util.telar.dev/api/avatars/" + userUUID.String(),
Banner: fmt.Sprintf("https://picsum.photos/id/%d/900/300/?blur", generateRandomNumber(1, 1000)),
Permission: constants.Public,
}
userProfileErr := saveUserProfile(newUserProfile)
if userProfileErr != nil {
log.Error("Save user profile %s", userProfileErr.Error())
return c.Status(http.StatusInternalServerError).JSON(utils.Error("canNotSaveUserProfile", fmt.Sprintf("Cannot save user profile! error: %s", userProfileErr.Error())))
}
setupErr := initUserSetup(newUserAuth.ObjectId, newUserAuth.Username, "", newUserProfile.FullName, newUserAuth.Role)
if setupErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("initUserSetupError", fmt.Sprintf("Cannot initialize user setup! error: %s", setupErr.Error())))
}
tokenModel := &TokenModel{
token: ProviderAccessToken{},
oauthProvider: nil,
providerName: *coreConfig.AppConfig.AppName,
profile: &provider.Profile{Name: fullName, ID: userId, Login: email},
organizationList: *coreConfig.AppConfig.OrgName,
claim: UserClaim{
DisplayName: fullName,
SocialName: socialName,
Email: email,
UserId: userId,
Role: "user",
Banner: newUserProfile.Banner,
TagLine: newUserProfile.TagLine,
CreatedDate: newUserProfile.CreatedDate,
},
}
session, sessionErr := createToken(tokenModel)
if sessionErr != nil {
errorMessage := fmt.Sprintf("Error creating session error: %s",
sessionErr.Error())
return c.Status(http.StatusBadRequest).JSON(utils.Error("initUserSetupError", errorMessage))
}
log.Info("\nSession is created: %s \n", session)
webURL := authConfig.AuthConfig.ExternalRedirectDomain
return c.Render("redirect", fiber.Map{
"URL": webURL,
})
}
// CheckAdminHandler creates a handler to check whether admin user registered
func CheckAdminHandler(c *fiber.Ctx) error {
//Create service
userAuthService, serviceErr := service.NewUserAuthService(database.Db)
if serviceErr != nil {
return c.Status(http.StatusInternalServerError).JSON(utils.Error("internal/userAuthService", serviceErr.Error()))
}
adminUser, checkErr := userAuthService.CheckAdmin()
if checkErr != nil {
errorMessage := fmt.Sprintf("Admin check error: %s",
checkErr.Error())
return c.Status(http.StatusInternalServerError).JSON(utils.Error("adminCheckError", errorMessage))
}
log.Info("Admin check: %v", adminUser)
adminExist := (adminUser.ObjectId != uuid.Nil)
return c.JSON(fiber.Map{
"admin": adminExist,
})
}
// renderCodeVerify return signup verify page
func renderCodeVerify(c *fiber.Ctx, data *signupVerifyPageData) error {
return c.Render("code_verification", fiber.Map{
"Title": data.title,
"OrgName": data.orgName,
"OrgAvatar": data.orgAvatar,
"AppName": data.appName,
"ActionForm": data.actionForm,
"SignupLink": "",
"Secret": data.token,
"Message": data.message,
})
}