-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathMasterUsersRoutes.go
339 lines (261 loc) · 9.71 KB
/
MasterUsersRoutes.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
package main
import (
"fmt"
"github.com/LiamDotPro/Go-Multitenancy/helpers"
"github.com/LiamDotPro/Go-Multitenancy/params"
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
"log"
"net/http"
"time"
)
// Init
func setupMasterUsersRoutes(router *gin.Engine) {
users := router.Group("/master/api/users")
// POST
users.POST("create", HandleMasterCreateUser)
users.POST("login", HandleMasterLoginAttempt(Store), HandleMasterLogin)
users.POST("updateUserDetails", HandleMasterUpdateUserDetails)
users.POST("createNewTenant", HandleCreateNewTenant)
users.POST("logout", HandleMasterLogout)
// GET
users.GET("getUserById", HandleMasterGetUserById)
users.GET("getCurrentUser", HandleMasterGetCurrentUser)
// DELETE
users.DELETE("deleteUser", HandleMasterDeleteUser)
}
// @Summary Create a new user
// @tags master/users
// @Router /master/api/users/create [post]
func HandleMasterCreateUser(c *gin.Context) {
// Binds Model and handles validation.
var json params.CreateUserParams
if err := c.ShouldBindJSON(&json); err != nil {
// Handle errors
c.JSON(http.StatusBadRequest, gin.H{"message": "Incorrect details supplied, please try again."})
return
}
if !helpers.ValidateEmail(json.Email) {
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
c.Abort()
return
}
// Validate the password being sent.
if len(json.Password) <= 7 {
c.JSON(http.StatusBadRequest, gin.H{"message": "The specified password was to short, must be longer than 8 characters."})
return
}
// Validate the password contains at least one letter and capital
if !helpers.ContainsCapitalLetter(json.Password) {
c.JSON(http.StatusBadRequest, gin.H{"message": "The specified password does not contain a capital letter."})
return
}
// Make sure the password contains at least one special character.
if !helpers.ContainsSpecialCharacter(json.Password) {
c.JSON(http.StatusBadRequest, gin.H{"message": "The password must contain at least one special character."})
return
}
// Attempt to create a user.
insertedId, err := createMasterUser(json.Email, json.Password, json.Type)
if err != nil {
// Handle the error and or return the context and include a server error status code.
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "The user has been successfully created.",
"userId": insertedId,
})
}
// @Summary Attempt to login using user details
// @tags master/users
// @Router /master/api/users/login [post]
func HandleMasterLogin(c *gin.Context) {
bindJson, _ := c.Get("bindedJson")
json := bindJson.(params.LoginParams)
if !helpers.ValidateEmail(json.Email) {
fmt.Println("A email address was not used to attempt login.")
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
c.Abort()
return
}
// Validate the password being sent.
if len(json.Password) <= 7 {
fmt.Println("Password is shorter then 8 characters")
c.JSON(http.StatusBadRequest, gin.H{"message": "The specified password was to short, must be longer than 8 characters."})
return
}
// Validate the password contains at least one letter and capital
if !helpers.ContainsCapitalLetter(json.Password) {
fmt.Println("No Capital letter used.")
c.JSON(http.StatusBadRequest, gin.H{"message": "The specified password does not contain a capital letter."})
return
}
// Make sure the password contains at least one special character.
if !helpers.ContainsSpecialCharacter(json.Password) {
fmt.Println("No special character found.")
c.JSON(http.StatusBadRequest, gin.H{"message": "The password must contain at least one special character."})
return
}
// Get our session from database.
session, exists := c.Get("session")
if !exists {
c.JSON(http.StatusUnprocessableEntity, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
return
}
userId, outcome, err := loginMasterUser(json.Email, json.Password)
if err != nil {
// Save changes to our session if an error occurred and we need to abort early..
if err := Store.Save(c.Request, c.Writer, session.(*sessions.Session)); err != nil {
fmt.Print(err)
}
// Were sending 422 as there is a validation concern.
c.JSON(http.StatusUnprocessableEntity, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
return
}
// Create a copy of the host profile
hostProfile := session.(*sessions.Session).Values["host"].(HostProfile)
// Set session values to authorized
hostProfile.Authorized = 1
hostProfile.AuthorizedTime = time.Now().UTC()
hostProfile.UserId = userId
// Reset login attempts once successfully logged in.
hostProfile.LoginAttempts[json.Email].LoginAttempts = 0
// Set host profile back to values.
session.(*sessions.Session).Values["host"] = hostProfile
// Save changes to our session.
if err := Store.Save(c.Request, c.Writer, session.(*sessions.Session)); err != nil {
fmt.Print(err)
}
c.JSON(http.StatusOK, gin.H{
"attempt": outcome,
"message": "You have successfully logged into your account.",
})
}
// @Summary Logs a user out of the system
// @tags master/users
// @Router /master/api/users/logout [post]
func HandleMasterLogout(c *gin.Context) {
// Binds Model and handles validation.
var json params.CreateUserParams
if err := c.ShouldBindJSON(&json); err != nil {
// Handle errors
c.JSON(http.StatusBadRequest, gin.H{"message": "Incorrect details supplied, please try again."})
return
}
// Get our session from database.
session, err := Store.Get(c.Request, "connect.s.id")
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
return
}
// Create a copy of the host profile
hostProfile := session.Values["host"].(HostProfile)
// Set session values to unauthorized
hostProfile.Authorized = 0
// Set host profile back to values.
session.Values["host"] = hostProfile
// Save changes to our session.
if err := Store.Save(c.Request, c.Writer, session); err != nil {
fmt.Print(err)
}
c.JSON(http.StatusOK, gin.H{
"message": "You have successfully logged out of your account.",
})
}
// @Summary Updates a users details
// @tags master/users
// @Router /master/api/users/updateUserDetails [post]
func HandleMasterUpdateUserDetails(c *gin.Context) {
var json params.UpdateUserParams
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "Missing required fields, please try again."})
log.Println(err)
return
}
outcome, err := updateMasterUser(json.Id, json.Email, json.AccountType, json.FirstName, json.LastName, json.PhoneNumber, json.RecoveryEmail)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again."})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": outcome,
})
}
// @Summary Deletes a user using a user id
// @tags master/users
// @Router /master/api/users/deleteUser [delete]
func HandleMasterDeleteUser(c *gin.Context) {
var json params.DeleteUserParams
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "Missing required fields, please try again."})
return
}
outcome, err := deleteMasterUser(json.Id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again."})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": outcome,
})
}
// @Summary Attempts to get a existing user by id
// @tags master/users
// @Router /master/api/users/getUserById [get]
func HandleMasterGetUserById(c *gin.Context) {
// Were using delete params as it shares the same interface.
var json params.DeleteUserParams
if err := c.Bind(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "No user ID found, please try again."})
return
}
outcome, err := getMasterUser(json.Id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Successfully found user",
"user": outcome,
})
}
// @Summary Attempts to get the currently logged in user using there session id.
// @tags master/users
// @Router /master/api/users/getCurrentUser [get]
func HandleMasterGetCurrentUser(c *gin.Context) {
// Get the currently logged int user id.
userId := c.MustGet("userId")
outcome, err := getMasterUser(userId.(uint))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Successfully found user",
"user": outcome,
})
}
// @Summary Attempts to create a new tenant as a privileged user.
// @tags master/users
// @Router /master/api/users/createNewTenant [Post]
func HandleCreateNewTenant(c *gin.Context) {
var json params.CreateNewTenantParams
if err := c.Bind(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "No subdomain identifier was found."})
return
}
outcome, err := createNewTenant(json.SubDomainIdentifier)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong while trying to process that, please try again.", "error": err.Error()})
log.Println(err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": outcome,
})
}