-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
50 lines (43 loc) · 1020 Bytes
/
jwt.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
package common
import (
"github.com/dgrijalva/jwt-go"
"github.com/empathy117/ship-of-hope/model"
"time"
)
// string
var key = []byte("empathy117")
type Claims struct {
UserId uint
jwt.StandardClaims
}
func GetToken(user model.User) (string, error) {
// expire time
expireTime := time.Now().Add(7 * 24 * time.Hour)
claims := &Claims{
UserId: user.ID,
StandardClaims: jwt.StandardClaims{
// expire time
ExpiresAt: expireTime.Unix(),
// release time
IssuedAt: time.Now().Unix(),
// issuer
Issuer: "empathy",
// subject
Subject: "user token",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
res, err := token.SignedString(key)
if err != nil {
return "", err
}
return res, nil
}
// ParseToken parse the token
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) {
return key, nil
})
return token, claims, err
}