-
Notifications
You must be signed in to change notification settings - Fork 12
/
LoginAttemptMiddleware.go
369 lines (295 loc) · 11 KB
/
LoginAttemptMiddleware.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
package main
import (
"fmt"
"github.com/LiamDotPro/Go-Multitenancy/helpers"
"github.com/LiamDotPro/Go-Multitenancy/params"
"github.com/gin-gonic/gin"
"github.com/wader/gormstore"
"net/http"
"time"
)
type ClientProfile struct {
LoginAttempts map[string]map[string]*loginAttempt // Key is email address
AuthorizationMap map[string]uint // Key is tenant identifier
}
type HostProfile struct {
LoginAttempts map[string]*loginAttempt // Key is used email address
LastLoginAttemptTime time.Time
AuthorizedTime time.Time
UserId uint
Authorized uint
}
type loginAttempt struct {
LastLoginAttemptTime time.Time
LoginAttempts uint
}
func newHostProfile() HostProfile {
h := HostProfile{}
h.LoginAttempts = make(map[string]*loginAttempt)
h.Authorized = 0
return h
}
func newClientProfile() ClientProfile {
c := ClientProfile{}
c.LoginAttempts = make(map[string]map[string]*loginAttempt)
c.AuthorizationMap = make(map[string]uint)
return c
}
// Checks if a user is logged in with a session to the master dashboard
func HandleMasterLoginAttempt(Store *gormstore.Store) gin.HandlerFunc {
return func(c *gin.Context) {
// Try and get a session.
sessionValues, err := Store.Get(c.Request, "connect.s.id")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
// Check to see if the user is already authorized..
if sessionValues.ID != "" {
p := sessionValues.Values["host"].(HostProfile)
if p.Authorized == 1 {
c.JSON(http.StatusOK, gin.H{
"outcome": "Already Authorized",
"message": "user already authorized with application.",
})
c.Abort()
return
}
}
// Check our parameters out.
var json params.LoginParams
// Abort if we don't have the correct variables to begin with.
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
fmt.Println("Can't bind request variables for login")
c.Abort()
return
}
if !helpers.ValidateEmail(json.Email) {
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
fmt.Println("Email is not in a valid format.")
c.Abort()
return
}
// Abort if the passed password is not correct.
// 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."})
c.Abort()
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."})
c.Abort()
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."})
c.Abort()
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
c.Set("bindedJson", json)
// Check to see if a new session is found.
if sessionValues.ID == "" {
// Setup new session with empty profiles.
session, err := Store.New(c.Request, "connect.s.id")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
// Host profile requires little setup
session.Values["host"] = newHostProfile()
// Add the entry record to hostProfile
session.Values["host"].(HostProfile).LoginAttempts[json.Email] = &loginAttempt{LoginAttempts: 1, LastLoginAttemptTime: time.Now().UTC()}
// Client profile requires no setup
session.Values["client"] = newClientProfile()
// Set the session back to the handler for use.
c.Set("session", session)
return
} else {
// Profile was already found
h := sessionValues.Values["host"].(HostProfile)
// Check if the email used is already in our login attempts.
loginAttemptsFound, found := h.LoginAttempts[json.Email]
if !found {
// email has not been used to login add a new entry
h.LoginAttempts[json.Email] = &loginAttempt{LoginAttempts: 1, LastLoginAttemptTime: time.Now().UTC()}
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
}
// Check to see if login attempts exceeds 3 attempts
if found && loginAttemptsFound.LoginAttempts > 2 {
// Check to see if last login attempt was over half an hour ago
if time.Now().Sub(loginAttemptsFound.LastLoginAttemptTime).Minutes() > 30 {
// reset login attempts to have 2 more.
loginAttemptsFound.LoginAttempts = 1
loginAttemptsFound.LastLoginAttemptTime = time.Now().UTC()
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
} else {
c.JSON(http.StatusInternalServerError, gin.H{"message": "You have been locked out for too many attempts to login..", "status": "locked out", "timeLeft": 30 - time.Now().Sub(loginAttemptsFound.LastLoginAttemptTime).Minutes()})
c.Abort()
return
}
}
if found && loginAttemptsFound.LoginAttempts <= 2 {
// increase login attempt count
loginAttemptsFound.LoginAttempts++
// replace last attempt date
loginAttemptsFound.LastLoginAttemptTime = time.Now().UTC()
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
}
}
}
}
// Checks if a user is logged in with a session to the client dashboard
func HandleLoginAttempt(Store *gormstore.Store) gin.HandlerFunc {
return func(c *gin.Context) {
// Try and get tenancy identifier
tenantIdentifier, found := c.Get("tenantIdentifier")
if !found {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
// Try and get a session.
sessionValues, err := Store.Get(c.Request, "connect.s.id")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
// Check to see if the user is already authorized..
if sessionValues.ID != "" {
p := sessionValues.Values["client"].(ClientProfile)
authorizationEntry := p.AuthorizationMap[tenantIdentifier.(string)]
if authorizationEntry == 1 {
c.JSON(http.StatusOK, gin.H{
"outcome": "Already Authorized",
"message": "user already authorized with application.",
})
c.Abort()
return
}
}
// Check our parameters out.
var json params.LoginParams
// Abort if we don't have the correct variables to begin with.
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
fmt.Println("Can't bind request variables for login")
c.Abort()
return
}
if !helpers.ValidateEmail(json.Email) {
c.JSON(http.StatusBadRequest, gin.H{"message": "Email or Password provided are incorrect, please try again."})
fmt.Println("Email is not in a valid format.")
c.Abort()
return
}
// Abort if the passed password is not correct.
// 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."})
c.Abort()
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."})
c.Abort()
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."})
c.Abort()
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
c.Set("bindedJson", json)
// Check to see if a new session is found.
if sessionValues.ID == "" {
// Setup new session with empty profiles.
session, err := Store.New(c.Request, "connect.s.id")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Something went wrong.."})
c.Abort()
return
}
// Host profile requires little setup
session.Values["host"] = newHostProfile()
// Client profile requires no setup
session.Values["client"] = newClientProfile()
session.Values["client"].(ClientProfile).LoginAttempts[tenantIdentifier.(string)] = make(map[string]*loginAttempt)
session.Values["client"].(ClientProfile).LoginAttempts[tenantIdentifier.(string)][json.Email] = &loginAttempt{LoginAttempts: 1, LastLoginAttemptTime: time.Now().UTC()}
// Set the session back to the handler for use.
c.Set("session", session)
return
} else {
// Profile was already found
h := sessionValues.Values["client"].(ClientProfile)
// Attempt to find tenant entry in login attempts.
tenantMap, found := h.LoginAttempts[tenantIdentifier.(string)]
if !found {
// Create a new entry for the tenant entry in map, also create login attempt
tenantMap = make(map[string]*loginAttempt)
tenantMap[json.Email] = &loginAttempt{LoginAttempts: 1, LastLoginAttemptTime: time.Now().UTC()}
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
}
// Check if the email used is already in our login attempts.
loginAttemptsFound, found := tenantMap[json.Email]
if !found {
// email has not been used to login add a new entry
loginAttemptsFound = &loginAttempt{LoginAttempts: 1, LastLoginAttemptTime: time.Now().UTC()}
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
}
// Check to see if login attempts exceeds 3 attempts
if found && loginAttemptsFound.LoginAttempts > 2 {
// Check to see if last login attempt was over half an hour ago
if time.Now().Sub(loginAttemptsFound.LastLoginAttemptTime).Minutes() > 30 {
// reset login attempts to have 2 more.
loginAttemptsFound.LoginAttempts = 1
loginAttemptsFound.LastLoginAttemptTime = time.Now().UTC()
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
} else {
c.JSON(http.StatusInternalServerError, gin.H{"message": "You have been locked out for too many attempts to login..", "status": "locked out", "timeLeft": 30 - time.Now().Sub(loginAttemptsFound.LastLoginAttemptTime).Minutes()})
c.Abort()
return
}
}
if found && loginAttemptsFound.LoginAttempts <= 2 {
// increase login attempt count
loginAttemptsFound.LoginAttempts++
// replace last attempt date
loginAttemptsFound.LastLoginAttemptTime = time.Now().UTC()
// Set the session back to the handler for use.
c.Set("session", sessionValues)
return
}
}
}
}