-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathUserRoutes.go
319 lines (241 loc) · 8.79 KB
/
UserRoutes.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
package main
import (
"fmt"
"github.com/LiamDotPro/Go-Multitenancy/helpers"
"github.com/LiamDotPro/Go-Multitenancy/middleware"
"github.com/LiamDotPro/Go-Multitenancy/params"
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm"
"log"
"net/http"
)
// Init
func setupUsersRoutes(router *gin.Engine) {
users := router.Group("/api/users")
// Turn on the need for tenancy finding.
users.Use(middleware.FindTenancy(Connection))
// POST
users.POST("create", HandleCreateUser)
users.POST("login", HandleLogin)
users.POST("updateUserDetails", HandleUpdateUserDetails)
users.POST("testPoster", HandleTestPoster)
// GET
users.GET("getUserById", HandleGetUserById)
users.GET("getCurrentUser", HandleGetCurrentUser)
users.GET("testGetter", HandleLoginAttempt(Store), HandleTestGetter)
// DELETE
users.DELETE("deleteUser", HandleDeleteUser)
}
// @Summary Create a new user
// @tags users
// @Router /api/users/create [post]
func HandleCreateUser(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
}
// Get the database object from the connection.
db, _ := c.Get("connection")
// Attempt to create a user.
insertedId, err := createUser(json.Email, json.Password, json.Type, db.(*gorm.DB))
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 users
// @Router /api/users/# [post]
func HandleLogin(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 the database object from the connection.
db, _ := c.Get("connection")
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 := loginUser(json.Email, json.Password, db.(*gorm.DB))
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
}
// @todo make this into a map so userid's can be multiple.
session.(*sessions.Session).Values["userId"] = userId
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 Updates a users details
// @tags users
// @Router /api/users/updateUserDetails [post]
func HandleUpdateUserDetails(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
}
// Get the database object from the connection.
db, _ := c.Get("connection")
outcome, err := updateUser(json.Id, json.Email, json.AccountType, json.FirstName, json.LastName, json.PhoneNumber, json.RecoveryEmail, db.(*gorm.DB))
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 users
// @Router /api/users/deleteUser [delete]
func HandleDeleteUser(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
}
// Get the database object from the connection.
db, _ := c.Get("connection")
outcome, err := deleteUser(json.Id, db.(*gorm.DB))
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 users
// @Router /api/users/getUserById [get]
func HandleGetUserById(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
}
// Get the database object from the connection.
db, _ := c.Get("connection")
outcome, err := getUser(json.Id, db.(*gorm.DB))
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 users
// @Router /api/users/getCurrentUser [get]
func HandleGetCurrentUser(c *gin.Context) {
// Get the currently logged int user id.
userId := c.MustGet("userId")
// Get the database object from the connection.
db, _ := c.Get("connection")
outcome, err := getUser(userId.(uint), db.(*gorm.DB))
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,
})
}
func HandleTestGetter(c *gin.Context) {
session, err := c.Get("session")
if !err {
fmt.Println("session not found")
}
fmt.Printf("%#v\n", session.(*sessions.Session).Values["client"])
fmt.Printf("%#v\n", session.(*sessions.Session).Values["client"].(ClientProfile).LoginAttempts["test"]["test@liam.pro"])
// 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{
"message": "Test Ran successfully",
})
}
func HandleTestPoster(c *gin.Context) {
sessionValues, err := Store.Get(c.Request, "connect.s.id")
if err != nil {
fmt.Println(err)
}
fmt.Printf("%#v\n", sessionValues)
c.JSON(http.StatusOK, gin.H{
"message": "Test Ran successfully",
})
}