-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
59 lines (52 loc) · 1.45 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
package kervan
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v4"
)
type LicenceCheckJWT struct {
LicenceKey string `json:"licence_key"`
IpAddress string `json:"ip_address"`
Data map[string]string `json:"data"`
jwt.RegisteredClaims
}
type LicenceCheckResponseJWT struct {
IsValid bool `json:"is_valid"`
PlanCode string `json:"plan_code"`
jwt.RegisteredClaims
}
func GenerateLicenceCheckJWT(licenceKey, ip_address string, data map[string]string, secret string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, LicenceCheckJWT{
LicenceKey: licenceKey,
IpAddress: ip_address,
Data: data,
RegisteredClaims: jwt.RegisteredClaims{
Audience: jwt.ClaimStrings{"kervan"},
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Minute)),
},
})
return token.SignedString([]byte(secret))
}
func ParseLicenceCheckResponseJWT(tokenString, secret string) (claims *LicenceCheckResponseJWT, err error) {
if tokenString == "" {
return nil, errors.New("tokenString is empty")
}
if secret == "" {
return nil, errors.New("secret is empty")
}
token, err := jwt.ParseWithClaims(
tokenString,
&LicenceCheckResponseJWT{},
func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
},
)
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*LicenceCheckResponseJWT)
if !ok {
return nil, errors.New("claims not LicenceCheckResponseJWT")
}
return claims, nil
}