-
Notifications
You must be signed in to change notification settings - Fork 1
/
login.go
323 lines (294 loc) · 9.26 KB
/
login.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
package auth
import (
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/BradHacker/compsole/api"
"github.com/BradHacker/compsole/ent"
"github.com/BradHacker/compsole/ent/action"
"github.com/BradHacker/compsole/ent/token"
"github.com/BradHacker/compsole/ent/user"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
// LocalLogin godoc
//
// @Summary Login with a local account
// @Schemes http https
// @Description Login with a local account
// @Tags Auth API
// @Accept json,mpfd
// @Param login body auth.UserLoginVals true "User account details"
// @Produce json
// @Success 200 {object} auth.UserModel
// @Header 200 {string} Cookie "`auth-cookie` contains the session token"
// @Router /auth/local/login [post]
func LocalLogin(client *ent.Client) gin.HandlerFunc {
return func(c *gin.Context) {
hostname, ok := os.LookupEnv("GRAPHQL_HOSTNAME")
if !ok {
hostname = "localhost"
}
cookie_timeout := 60
if env_value, exists := os.LookupEnv("COOKIE_TIMEOUT"); exists {
if atio_value, err := strconv.Atoi(env_value); err == nil {
cookie_timeout = atio_value
}
}
secure_cookie := false
if env_value, exists := os.LookupEnv("HTTPS_ENABLED"); exists {
if env_value == "true" {
secure_cookie = true
}
}
var loginVals UserLoginVals
username := ""
password := ""
if err := c.ShouldBind(&loginVals); err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
return
} else {
username = loginVals.Username
password = loginVals.Password
}
// Get the client's IP address
clientIp, err := api.ForContextIp(c)
if err != nil {
logrus.Warnf("failed to get IP from gin context: %v", err)
}
entUser, err := client.User.Query().Where(
user.And(
user.UsernameEQ(username),
user.ProviderEQ(user.ProviderLOCAL),
),
).
WithUserToTeam().
Only(c)
if ent.IsNotFound(err) {
err = client.Action.Create().
SetIPAddress(clientIp).
SetType(action.TypeFAILED_SIGN_IN).
SetMessage(fmt.Sprintf("user \"%s\" does not exists", username)).
SetActionToUser(entUser).
Exec(c)
if err != nil {
logrus.Warn("failed to create FAILED_SIGN_IN action: %v", err)
}
}
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
return
}
// Compare the stored hashed password, with the hashed version of the password that was received
if err = bcrypt.CompareHashAndPassword([]byte(entUser.Password), []byte(password)); err != nil {
err = client.Action.Create().
SetIPAddress(clientIp).
SetType(action.TypeFAILED_SIGN_IN).
SetMessage(fmt.Sprintf("wrong password for user \"%s\"", username)).
SetActionToUser(entUser).
Exec(c)
if err != nil {
logrus.Warn("failed to create FAILED_SIGN_IN action: %v", err)
}
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
return
}
expiresAt := time.Now().Add(time.Minute * time.Duration(cookie_timeout)).Unix()
claims := &api.CompsoleJWTClaims{
IssuedAt: time.Now().Unix(),
StandardClaims: jwt.StandardClaims{
ExpiresAt: expiresAt,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
jwtKey, exists := os.LookupEnv("JWT_SECRET")
if !exists {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
logrus.Warn("env var JWT_SECRET is not set")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Error signing token"})
return
}
tokenString, err := token.SignedString([]byte(jwtKey))
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
logrus.Errorf("error signing token: %v", err)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Error signing token"})
return
}
_, err = client.Token.Create().SetTokenToUser(entUser).SetExpireAt(expiresAt).SetToken(tokenString).Save(c)
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Error updating token"})
return
}
if secure_cookie {
c.SetCookie("auth-cookie", tokenString, cookie_timeout*60, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", tokenString, cookie_timeout*60, "/", hostname, false, false)
}
// Successful sign-in
err = client.Action.Create().
SetIPAddress(clientIp).
SetType(action.TypeSIGN_IN).
SetMessage(fmt.Sprintf("user \"%s\" has signed in successfully", username)).
SetActionToUser(entUser).
Exec(c)
if err != nil {
logrus.Warn("failed to create SIGN_IN action: %v", err)
}
entUser.Password = ""
c.JSON(200, UserEntToModel(entUser))
c.Next()
}
}
// Logout decodes the share session cookie and packs the session into context
func Logout(client *ent.Client) gin.HandlerFunc {
return func(c *gin.Context) {
hostname, ok := os.LookupEnv("GRAPHQL_HOSTNAME")
if !ok {
hostname = "localhost"
}
secure_cookie := false
if env_value, exists := os.LookupEnv("HTTPS_ENABLED"); exists {
if env_value == "true" {
secure_cookie = true
}
}
authCookie, err := c.Cookie("auth-cookie")
// Allow unauthenticated users in
if err != nil || authCookie == "" {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
return
}
// Get the JWT string from the cookie
tknStr := authCookie
// Initialize a new instance of `Claims`
claims := &api.CompsoleJWTClaims{}
jwtKey, exists := os.LookupEnv("JWT_SECRET")
if !exists {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Parse the JWT string and store the result in `claims`.
// Note that we are passing the key in this method as well. This method will return an error
// if the token is invalid (if it has expired according to the expiry time we set on sign in),
// or if the signature does not match
tkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(jwtKey), nil
})
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
if err == jwt.ErrSignatureInvalid {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.AbortWithStatus(http.StatusBadRequest)
return
}
if !tkn.Valid {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Get the user and log a sign out event
entUser, err := client.User.Query().Where(user.HasUserToTokenWith(token.TokenEQ(authCookie))).Only(c)
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
return
}
clientIpValues, exists := c.Request.Header["X-Forwarded-For"]
clientIp := ""
if exists {
clientIp = clientIpValues[0]
} else {
clientIp = c.RemoteIP()
}
err = client.Action.Create().
SetIPAddress(clientIp).
SetType(action.TypeSIGN_OUT).
SetMessage(fmt.Sprintf("user \"%s\" has signed out", entUser.Username)).
SetActionToUser(entUser).
Exec(c)
if err != nil {
logrus.Warn("failed to create SIGN_OUT action: %v", err)
}
_, err = client.Token.Delete().Where(token.TokenEQ(authCookie)).Exec(c)
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
return
}
if err != nil {
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Error updating token"})
return
}
if secure_cookie {
c.SetCookie("auth-cookie", "", 0, "/", hostname, true, true)
} else {
c.SetCookie("auth-cookie", "", 0, "/", hostname, false, false)
}
c.Next()
}
}