-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
125 lines (94 loc) · 2.28 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package generator
import (
"crypto/rand"
"encoding/base64"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
// AccessInput struct
type AccessInput struct {
UserKey string
ClientKey string
SecretToken string
Expiry int64
}
// TokenOutput struct
type TokenOutput struct {
Token string
CreatedOn int64
}
// TokenClaims data struct
type tokenClaims struct {
UserKey string `json:"user_id"`
ClientKey string `json:"client_id"`
jwt.StandardClaims
}
// Token interface
type Token interface {
Generate() (TokenOutput, error)
}
// Access interface
type Access interface {
Generate(i AccessInput) (TokenOutput, error)
}
type access struct{}
func (g access) Generate(i AccessInput) (TokenOutput, error) {
var output TokenOutput
now := time.Now()
claims := tokenClaims{
i.UserKey,
i.ClientKey,
jwt.StandardClaims{
IssuedAt: now.Unix(),
ExpiresAt: now.Add(time.Second * time.Duration(i.Expiry)).Unix(),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(i.SecretToken))
if err != nil {
return output, err
}
output = TokenOutput{
Token: token,
CreatedOn: now.Unix(),
}
return output, nil
}
type token struct {
length int
}
func (g token) Generate() (TokenOutput, error) {
var output TokenOutput
token, err := g.generateRandomString()
if err != nil {
return output, err
}
output = TokenOutput{
Token: token,
CreatedOn: time.Now().Unix(),
}
return output, nil
}
func (g token) generateRandomString() (string, error) {
bytes, err := g.generateRandomBytes()
return base64.URLEncoding.EncodeToString(bytes), err
}
func (g token) generateRandomBytes() ([]byte, error) {
bytes := make([]byte, g.length)
_, err := rand.Read(bytes)
if err != nil {
return nil, err
}
return bytes, nil
}
// GenerateToken method
func GenerateToken(g Token) (TokenOutput, error) { return g.Generate() }
// GenerateAccess method
func GenerateAccess(a Access, i AccessInput) (TokenOutput, error) { return a.Generate(i) }
// AccessToken method
func AccessToken() Access { return access{} }
// RefreshToken method
func RefreshToken(l int) Token { return token{length: l} }
// SecretToken method
func SecretToken(l int) Token { return token{length: l} }
// APIToken method
func APIToken(l int) Token { return token{length: l} }