forked from dbaseqp/Quotient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication.go
328 lines (275 loc) · 7.83 KB
/
authentication.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
package main
import (
"errors"
"fmt"
"net/http"
"strings"
"os"
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/go-ldap/ldap/v3"
"github.com/golang-jwt/jwt/v4"
)
type MyJWTClaims struct {
*jwt.RegisteredClaims
UserInfo interface{}
}
type UserJWTData struct {
Username string
ID uint
Admin bool
}
var (
privateKey []byte
publicKey []byte
)
func create(sub string, userInfo interface{}) (string, error) {
key, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey)
if err != nil {
return "", fmt.Errorf("create: parse key: %w", err)
}
exp := time.Now().Add(time.Hour * 24)
claims := &MyJWTClaims{
&jwt.RegisteredClaims{
Subject: sub,
ExpiresAt: jwt.NewNumericDate(exp),
},
userInfo,
}
token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
if err != nil {
return "", fmt.Errorf("create: sign token: %w", err)
}
return token, nil
}
func getClaimsFromToken(tokenString string) (jwt.MapClaims, error) {
key, err := jwt.ParseRSAPublicKeyFromPEM(publicKey)
if err != nil {
return nil, fmt.Errorf("get claims: parse key: %w", err)
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return claims, nil
}
return nil, err
}
func readKeyFiles() ([]byte, []byte, error) {
prvKey, err := os.ReadFile(eventConf.JWTPrivateKey)
if err != nil {
fmt.Println(err)
return nil, nil, err
}
pubKey, err := os.ReadFile(eventConf.JWTPublicKey)
if err != nil {
fmt.Println(err)
return nil, nil, err
}
return prvKey, pubKey, nil
}
func initCookies(router *gin.Engine) {
router.Use(sessions.Sessions("quotient", cookie.NewStore([]byte("quotient"))))
}
func login(c *gin.Context) {
var err error
session := sessions.Default(c)
var jsonData map[string]interface{}
if err := c.ShouldBindJSON(&jsonData); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing fields"})
return
}
username := jsonData["username"].(string)
password := jsonData["password"].(string)
// Validate form input
if strings.Trim(username, " ") == "" || strings.Trim(password, " ") == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Username or password can't be empty."})
return
}
// Authenticate user
var isAdmin bool
var teamid uint
if eventConf.LdapConnectUrl != "" {
teamid, isAdmin, err = ldapLogin(username, password)
if err != nil {
debugPrint("LDAP ERROR:", err)
}
}
// user still not found yet
if !isAdmin && teamid == 0 {
for _, admin := range eventConf.Admin {
if username == admin.Name && password == admin.Pw {
isAdmin = true
break
}
}
if !isAdmin {
teamid, err = dbLogin(username, password)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Incorrect username or password."})
return
}
}
}
session.Set("id", username)
jwtContent := UserJWTData{
Username: username,
Admin: isAdmin,
ID: teamid,
}
tok, err := create(username, jwtContent)
if err != nil {
fmt.Println(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate JWT"})
return
}
c.SetCookie("auth_token", tok, 86400, "/", "*", false, false)
if err := session.Save(); err != nil {
fmt.Println(err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "redirect": "/"})
}
func ldapLogin(username string, password string) (uint, bool, error) {
ldapServer, err := ldap.DialURL(eventConf.LdapConnectUrl)
if err != nil {
// c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return 0, false, err
}
defer ldapServer.Close()
err = ldapServer.Bind(eventConf.LdapBindDn, eventConf.LdapBindPassword)
if err != nil {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Incorrect username or password."})
return 0, false, err
}
// search for dn based on SAM
searchRequest := ldap.NewSearchRequest(
eventConf.LdapBaseDn, // baseDN
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(samaccountname=%s)", username), // filter
[]string{"cn", "memberOf"}, // attributes to retrieve
nil,
)
searchResult, err := ldapServer.Search(searchRequest)
if err != nil {
// c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return 0, false, err
}
// Check if user was found (which should always be true if it binded)
if len(searchResult.Entries) == 0 {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Incorrect username or password."})
return 0, false, errors.New("incorrect username or password")
}
// test bind
err = ldapServer.Bind(searchResult.Entries[0].DN, password) // test correct password
if err != nil {
// c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Incorrect username or password."})
return 0, false, err
}
var isAdmin bool
var teamid uint
// Print group membership
for _, entry := range searchResult.Entries {
for _, memberOf := range entry.GetAttributeValues("memberOf") {
if strings.EqualFold(memberOf, eventConf.LdapAdminGroupDn) {
isAdmin = true
break
}
if strings.EqualFold(memberOf, eventConf.LdapTeamGroupDn) {
team, err := dbGetTeam(entry.GetAttributeValue("cn"))
if err != nil {
// c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return 0, false, err
}
teamid = team.ID
break
}
}
}
return teamid, isAdmin, nil
}
func logout(c *gin.Context) {
session := sessions.Default(c)
id := session.Get("id")
cookie, err := c.Request.Cookie("auth_token")
if cookie != nil && err == nil {
c.SetCookie("auth_token", "", -1, "/", "*", false, true)
}
err = session.Save()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
if id == nil {
c.JSON(http.StatusOK, gin.H{"message": "No session."})
return
}
session.Delete("id")
if err := session.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save session"})
return
}
c.Redirect(http.StatusSeeOther, "/")
}
func isLoggedIn(c *gin.Context) (bool, error) {
tok, err := c.Cookie("auth_token")
if err != nil {
return false, nil
}
_, err = getClaimsFromToken(tok)
if err != nil {
return false, err
}
return true, nil
}
func authRequired(c *gin.Context) {
status, err := isLoggedIn(c)
if status == false || err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
c.Next()
}
func contextGetClaims(c *gin.Context) (UserJWTData, error) {
isLoggedIn, err := isLoggedIn(c)
if err != nil {
return UserJWTData{}, err
}
if isLoggedIn == false {
return UserJWTData{}, errors.New("not logged in")
}
tokenString, err := c.Cookie("auth_token")
if err != nil {
return UserJWTData{}, err
}
claims, err := getClaimsFromToken(tokenString)
if err != nil {
return UserJWTData{}, err
}
if val, ok := claims["UserInfo"]; ok {
userInfo := val.(map[string]interface{})
return UserJWTData{ID: uint(userInfo["ID"].(float64)), Username: userInfo["Username"].(string), Admin: userInfo["Admin"].(bool)}, nil
}
return UserJWTData{}, errors.New("no user info")
}
func adminAuthRequired(c *gin.Context) {
claims, err := contextGetClaims(c)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
if claims.Admin == false {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
c.Next()
}