-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
44 lines (35 loc) · 936 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
package main
import (
"errors"
"time"
"github.com/golang-jwt/jwt"
)
type Claims struct {
UserID int
jwt.StandardClaims
}
func GenerateToken(id int) (string, error) {
expire := time.Now().Add(time.Duration(JWTLifetime) * time.Minute)
claims := &Claims{
UserID: id,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expire.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(JWTSecret)
return tokenString, err
}
func ValidateToken(tokenString string) (int, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return JWTSecret, nil
})
if err != nil {
return 0, err
}
if !token.Valid {
return 0, errors.New("invalid access token")
}
return claims.UserID, nil
}