-
-
Notifications
You must be signed in to change notification settings - Fork 237
/
token.go
57 lines (46 loc) · 1.12 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
package service
import (
"fmt"
"strconv"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/saltbo/gopkg/jwtutil"
)
type Token struct {
}
func NewToken() *Token {
jwtutil.Init("123")
return &Token{}
}
func (s *Token) Create(uid string, ttl int, roles ...string) (string, error) {
return jwtutil.Issue(NewRoleClaims(uid, ttl, roles))
}
func (s *Token) Verify(tokenStr string) (*RoleClaims, error) {
token, err := jwtutil.Verify(tokenStr, &RoleClaims{})
if err != nil {
return nil, fmt.Errorf("token valid failed: %s", err)
}
return token.Claims.(*RoleClaims), nil
}
type RoleClaims struct {
jwt.StandardClaims
Roles []string `json:"roles"`
}
func NewRoleClaims(subject string, ttl int, roles []string) *RoleClaims {
timeNow := time.Now()
return &RoleClaims{
StandardClaims: jwt.StandardClaims{
Issuer: "zplat",
Audience: "zplatUsers",
ExpiresAt: timeNow.Add(time.Duration(ttl) * time.Second).Unix(),
IssuedAt: timeNow.Unix(),
NotBefore: timeNow.Unix(),
Subject: subject,
},
Roles: roles,
}
}
func (rc *RoleClaims) Uid() int64 {
uid, _ := strconv.ParseInt(rc.Subject, 10, 64)
return uid
}