-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth.go
96 lines (83 loc) · 2.06 KB
/
auth.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
package neocortex
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"time"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
)
type login struct {
Username string `form:"username" json:"username" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
type user struct {
Username string
}
const identityKey = "id"
func getJWTAuth(engine *Engine, secretKey string) *jwt.GinJWTMiddleware {
authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte(secretKey),
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: identityKey,
PayloadFunc: func(data interface{}) jwt.MapClaims {
if v, ok := data.(*user); ok {
return jwt.MapClaims{
identityKey: v.Username,
}
}
return jwt.MapClaims{}
},
IdentityHandler: func(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
return &user{
Username: claims["id"].(string),
}
},
Authenticator: func(c *gin.Context) (interface{}, error) {
data, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return "", errors.New(err.Error())
}
l := new(login)
if l == nil {
return nil, jwt.ErrFailedAuthentication
}
err = json.Unmarshal(data, l)
if err != nil {
return "", errors.New(err.Error())
}
userID := l.Username
password := l.Password
passwordAdmin, err := engine.getAdmin(userID)
if err != nil || passwordAdmin == "" {
return nil, jwt.ErrFailedAuthentication
}
if password == passwordAdmin {
return &user{
Username: userID,
}, nil
}
return nil, jwt.ErrFailedAuthentication
},
Authorizator: func(data interface{}, c *gin.Context) bool {
return true
},
Unauthorized: func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
},
TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
})
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
return authMiddleware
}