This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.go
100 lines (90 loc) · 2.36 KB
/
index.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
package auth
import (
"github.com/gogf/gf-jwt"
"github.com/gogf/gf/g"
"github.com/gogf/gf/g/net/ghttp"
"github.com/gogf/gf/g/util/gvalid"
"log"
"net/http"
"time"
)
type Default struct {
GfJWTMiddleware *jwt.GfJWTMiddleware
Rules map[string]string
}
func (d *Default) Init() {
authMiddleware, err := jwt.New(&jwt.GfJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Minute * 5,
MaxRefresh: time.Minute * 5,
IdentityKey: "id",
TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
Authenticator: d.Authenticator,
LoginResponse: d.LoginResponse,
RefreshResponse: d.RefreshResponse,
Unauthorized: d.Unauthorized,
IdentityHandler: d.IdentityHandler,
PayloadFunc: d.PayloadFunc,
})
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
d.GfJWTMiddleware = authMiddleware
d.Rules = map[string]string{
"username": "required",
"password": "required",
}
}
func (d *Default) PayloadFunc(data interface{}) jwt.MapClaims {
claims := jwt.MapClaims{}
params := data.(map[string]interface{})
if len(params) > 0 {
for k, v := range params {
claims[k] = v
}
}
return claims
}
func (d *Default) IdentityHandler(r *ghttp.Request) interface{} {
claims := jwt.ExtractClaims(r)
return claims["id"]
}
func (d *Default) Unauthorized(r *ghttp.Request, code int, message string) {
r.Response.WriteJson(g.Map{
"code": code,
"msg": message,
})
r.ExitAll()
}
func (d *Default) LoginResponse(r *ghttp.Request, code int, token string, expire time.Time) {
r.Response.WriteJson(g.Map{
"code": http.StatusOK,
"token": token,
"expire": expire.Format(time.RFC3339),
})
r.ExitAll()
}
func (d *Default) RefreshResponse(r *ghttp.Request, code int, token string, expire time.Time) {
r.Response.WriteJson(g.Map{
"code": http.StatusOK,
"token": token,
"expire": expire.Format(time.RFC3339),
})
r.ExitAll()
}
func (d *Default) Authenticator(r *ghttp.Request) (interface{}, error) {
data := r.GetMap()
if e := gvalid.CheckMap(data, d.Rules); e != nil {
return "", jwt.ErrFailedAuthentication
}
if data["username"] == "admin" && data["password"] == "admin" {
return g.Map {
"username": data["username"],
"id": data["username"],
}, nil
}
return nil, jwt.ErrFailedAuthentication
}