-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
232 lines (195 loc) · 6.93 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package logic
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt"
"github.com/maxuanquang/ojs/internal/configs"
"github.com/maxuanquang/ojs/internal/dataaccess/cache"
"github.com/maxuanquang/ojs/internal/dataaccess/database"
"github.com/maxuanquang/ojs/internal/utils"
"go.uber.org/zap"
)
type TokenLogic interface {
CreateTokenString(ctx context.Context, accountID uint64, accountName string, accountRole int8) (string, time.Time, error)
VerifyTokenString(ctx context.Context, token string) (accountId uint64, accountName string, accountRole int8, expiresAt time.Time, err error)
WithDatabase(database database.Database) TokenLogic
}
func NewTokenLogic(
accountDataAccessor database.AccountDataAccessor,
tokenPublicKeyDataAccessor database.TokenPublicKeyDataAccessor,
logger *zap.Logger,
authConfig configs.Auth,
tokenPublicKeyCache cache.TokenPublicKey,
) (TokenLogic, error) {
rsaKeyPair, err := generateRSAKeyPair(int(authConfig.Token.RS512KeyPairBitSize))
if err != nil {
logger.Error("failed to genereate RSA key pair", zap.Error(err))
return nil, err
}
publicKeyBytes, err := pemEncodePublicKey(&rsaKeyPair.PublicKey)
if err != nil {
logger.Error("failed to encode public key in pem format", zap.Error(err))
return nil, err
}
tokenPublicKeyID, err := tokenPublicKeyDataAccessor.CreatePublicKey(
context.Background(),
database.TokenPublicKey{
TokenPublicKeyValue: publicKeyBytes,
})
if err != nil {
logger.Error("failed to create token public key", zap.Error(err))
return nil, err
}
err = tokenPublicKeyCache.Set(context.Background(), fmt.Sprint(tokenPublicKeyID), publicKeyBytes)
if err != nil {
logger.With(zap.Error(err)).Warn("can not set token public key in cache")
}
return &tokenLogic{
accountDataAccessor: accountDataAccessor,
tokenPublicKeyDataAccessor: tokenPublicKeyDataAccessor,
logger: logger,
authConfig: authConfig,
tokenPublicKeyID: tokenPublicKeyID,
tokenPrivateKeyValue: rsaKeyPair,
tokenPublicKeyCache: tokenPublicKeyCache,
}, nil
}
type tokenLogic struct {
accountDataAccessor database.AccountDataAccessor
tokenPublicKeyDataAccessor database.TokenPublicKeyDataAccessor
logger *zap.Logger
authConfig configs.Auth
tokenPublicKeyID uint64
tokenPrivateKeyValue *rsa.PrivateKey
tokenPublicKeyCache cache.TokenPublicKey
}
// VerifyTokenString implements Token.
func (t *tokenLogic) VerifyTokenString(ctx context.Context, tokenString string) (uint64, string, int8, time.Time, error) {
logger := utils.LoggerWithContext(ctx, t.logger)
keyFunc := func(parsedToken *jwt.Token) (interface{}, error) {
if _, ok := parsedToken.Method.(*jwt.SigningMethodRSA); !ok {
logger.Error("unexpected signing method")
return nil, errors.New("unexpected signing method")
}
claims, ok := parsedToken.Claims.(jwt.MapClaims)
if !ok {
logger.Error("cannot get token's claims")
return nil, errors.New("cannot get token's claims")
}
tokenPublicKeyID, ok := claims["kid"].(float64)
if !ok {
logger.Error("cannot get token's kid claim")
return nil, errors.New("cannot get token's kid claim")
}
tokenPublicKeyValue, err := t.getJWTPublicKeyValue(ctx, uint64(tokenPublicKeyID))
if err != nil {
logger.Error("cannot get public key's value")
return nil, err
}
return tokenPublicKeyValue, nil
}
parsedToken, err := jwt.Parse(tokenString, keyFunc)
if err != nil {
logger.Error("cannot parse token", zap.Error(err))
return 0, "", 0, time.Time{}, err
}
if !parsedToken.Valid {
logger.Error("invalid token")
return 0, "", 0, time.Time{}, errors.New("invalid token")
}
claims, ok := parsedToken.Claims.(jwt.MapClaims)
if !ok {
logger.Error("cannot get token's claims")
return 0, "", 0, time.Time{}, errors.New("cannot get token's claims")
}
accountID, ok := claims["sub"].(float64)
if !ok {
logger.Error("cannot get token's sub claim")
return 0, "", 0, time.Time{}, errors.New("cannot get token's sub claim")
}
accountName, ok := claims["name"].(string)
if !ok {
logger.Error("cannot get token's name claim")
return 0, "", 0, time.Time{}, errors.New("cannot get token's name claim")
}
accountRole, ok := claims["role"].(float64)
if !ok {
logger.Error("cannot get token's role claim")
return 0, "", 0, time.Time{}, errors.New("cannot get token's role claim")
}
expiresAtUnix, ok := claims["exp"].(float64)
if !ok {
logger.Error("cannot get token's exp claim")
return 0, "", 0, time.Time{}, errors.New("cannot get token's exp claim")
}
return uint64(accountID), accountName, int8(accountRole), time.Unix(int64(expiresAtUnix), 0), nil
}
// CreateTokenString implements Token.
func (t *tokenLogic) CreateTokenString(ctx context.Context, accountID uint64, accountName string, accountRole int8) (string, time.Time, error) {
logger := utils.LoggerWithContext(ctx, t.logger)
expiresAt := time.Now().Add(t.authConfig.Token.GetTokenDuration())
token := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.MapClaims{
"sub": accountID,
"name": accountName,
"role": accountRole,
"exp": expiresAt.Unix(),
"kid": t.tokenPublicKeyID,
})
tokenString, err := token.SignedString(t.tokenPrivateKeyValue)
if err != nil {
logger.Error("failed signing token", zap.Error(err))
return "", time.Time{}, nil
}
return tokenString, expiresAt, nil
}
// WithDatabase implements Token.
func (t *tokenLogic) WithDatabase(database database.Database) TokenLogic {
panic("unimplemented")
}
func (t *tokenLogic) getJWTPublicKeyValue(ctx context.Context, tokenPublicKeyID uint64) (*rsa.PublicKey, error) {
logger := utils.LoggerWithContext(ctx, t.logger).With(zap.Uint64("tokenPublicKeyID", tokenPublicKeyID))
var tokenPublicKeyValue database.TokenPublicKey
cacheHit := true
bytes, err := t.tokenPublicKeyCache.Get(ctx, fmt.Sprintf("%d", tokenPublicKeyID))
if err != nil {
logger.With(zap.Error(err)).Warn("failed to get tokenPublicKeyValue from cache, will fall back to database")
cacheHit = false
} else {
tokenPublicKeyValue = database.TokenPublicKey{
TokenPublicKeyID: tokenPublicKeyID,
TokenPublicKeyValue: bytes,
}
}
if !cacheHit {
tokenPublicKeyValue, err = t.tokenPublicKeyDataAccessor.GetPublicKey(ctx, tokenPublicKeyID)
if err != nil {
logger.Error("cannot get token's public key from database", zap.Error(err))
return nil, err
}
}
return jwt.ParseRSAPublicKeyFromPEM(tokenPublicKeyValue.TokenPublicKeyValue)
}
func pemEncodePublicKey(pubKey *rsa.PublicKey) ([]byte, error) {
pubBytes, err := x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
return nil, err
}
block := &pem.Block{
Type: "PUBLIC KEY",
Bytes: pubBytes,
}
return pem.EncodeToMemory(block), nil
}
func generateRSAKeyPair(bits int) (*rsa.PrivateKey, error) {
privateKeyPair, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, err
}
return privateKeyPair, nil
}