-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
executable file
·80 lines (67 loc) · 1.54 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
package jwt
import (
"errors"
"strconv"
"strings"
"time"
jwtgo "github.com/dgrijalva/jwt-go"
)
var _signingKey []byte
var _expireSecond time.Duration
// Default Setup
func init() {
Setup("123456", 600)
}
// Setup : privatte key , and expire second
func Setup(key string, t time.Duration) {
_signingKey = []byte(key)
_expireSecond = t
}
// Build ...
func Build(in map[string]string) (token string, err error) {
exp := timeToString(time.Now().Add(_expireSecond))
claims := jwtgo.MapClaims{"exp": exp}
for k, v := range in {
claims[k] = v
}
return jwtgo.NewWithClaims(jwtgo.SigningMethodHS256, claims).SignedString(_signingKey)
}
// Verify ...
func Verify(tokenString string) (result map[string]string, err error) {
tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
token, err := jwtgo.Parse(tokenString, func(token *jwtgo.Token) (interface{}, error) {
return _signingKey, nil
})
if err != nil {
return
}
claims := token.Claims.(jwtgo.MapClaims)
exp, ok := claims["exp"].(string)
if !ok {
err = errors.New("parse fail")
return
}
if exp < timeToString(time.Now()) {
err = errors.New("exp fail : out of valid range")
return
}
result = map[string]string{}
for k := range claims {
v, ok := claims[k].(string)
if !ok {
err = errors.New("parse fail")
return
}
result[k] = v
}
return result, nil
}
// -- private function ------------
func timeToString(t time.Time) (timeStr string) {
v, _ := strconv.ParseInt(
strconv.FormatInt(t.UTC().UnixNano(), 10)[:13],
10,
64,
)
return strconv.Itoa(int(v))
}