-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
107 lines (84 loc) · 1.92 KB
/
token.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
package token
import (
"errors"
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
jwtlib "github.com/golang-jwt/jwt/v4"
)
func NewJwt(cfg JwtCfg) *Jwt {
return &Jwt{
Cfg: cfg,
}
}
// JwtCfg defines a token generator object
type JwtCfg struct {
EncKey []byte
// Expiration minutes
Exp int
Claims interface{}
}
type Jwt struct {
Cfg JwtCfg
}
// Tok is a token
type Tok struct {
Claims jwtlib.MapClaims
Valid bool
Err error
}
// GetToken generated a HS256 token from an object
func (jwt *Jwt) GetToken(v interface{}) (string, error) {
// make a token
token := jwtlib.New(jwtlib.GetSigningMethod("HS256"))
time.Local = time.UTC
token.Claims = jwtlib.MapClaims{
"data": v,
"exp": time.Now().Unix() + (int64(jwt.Cfg.Exp) * 60),
}
tokenString, err := token.SignedString(jwt.Cfg.EncKey)
return tokenString, err
}
// GinHandler is a middleware for Gin-gonic
func (jwt *Jwt) GinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
claims, err := jwt.GinParse(c)
tok := &Tok{
Claims: claims,
Valid: true,
Err: err,
}
if err != nil {
tok.Err = err
tok.Valid = false
}
c.Set("Tok", tok)
}
}
// GinParse parses a gin.Context
func (jwt *Jwt) GinParse(c *gin.Context) (map[string]interface{}, error) {
var (
claims jwtlib.MapClaims
tokStr = ""
)
authHeader := strings.Split(c.GetHeader("Authorization"), " ")
if len(authHeader) > 1 && authHeader[0] == "Bearer" {
tokStr = authHeader[1]
}
if len(tokStr) > 0 {
token, err := jwtlib.Parse(tokStr, func(token *jwtlib.Token) (interface{}, error) {
if _, ok := token.Method.(*jwtlib.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return jwt.Cfg.EncKey, nil
})
if err != nil {
return claims, err
}
if claims, ok := token.Claims.(jwtlib.MapClaims); ok && token.Valid {
return claims, nil
}
}
return claims, errors.New("invalid token")
}