-
Notifications
You must be signed in to change notification settings - Fork 4
/
jwt.go
86 lines (66 loc) · 1.69 KB
/
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
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
package jwt
import (
"errors"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/wearedevx/keystone/api/pkg/models"
)
var salt string
var (
ErrorInvalidToken = errors.New("invalid token")
ErrorTokenExpired = errors.New("token expired")
)
type customClaims struct {
DeviceUID string `json:"device_uid"`
jwt.StandardClaims
}
func MakeToken(user models.User, deviceUID string, when time.Time) (string, error) {
salt := []byte(salt)
claims := customClaims{
DeviceUID: deviceUID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: when.Add(30 * 24 * time.Hour).Unix(),
IssuedAt: when.Unix(),
Issuer: "keystone",
Subject: user.UserID,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(salt)
}
func cleanUpToken(token string) string {
if strings.HasPrefix(token, "Bearer ") {
s := strings.Replace(token, "Bearer ", "", 1)
return strings.Trim(s, " ")
}
return strings.Trim(token, " ")
}
func VerifyToken(token string) (string, string, error) {
trimedToken := cleanUpToken(token)
t, err := jwt.Parse(
trimedToken,
func(token *jwt.Token) (interface{}, error) {
return []byte(salt), nil
},
)
if err != nil {
if validationError, ok := err.(jwt.ValidationError); ok {
if validationError.Errors&jwt.ValidationErrorExpired == jwt.ValidationErrorExpired {
return "", "", ErrorTokenExpired
}
} else {
return "", "", err
}
}
if t.Valid {
claims := t.Claims.(jwt.MapClaims)
userID := claims["sub"].(string)
if claims["device_uid"] == nil {
return "", "", ErrorTokenExpired
}
deviceUID := claims["device_uid"].(string)
return userID, deviceUID, nil
}
return "", "", ErrorInvalidToken
}