-
Notifications
You must be signed in to change notification settings - Fork 1
/
refresh_token.go
68 lines (54 loc) · 1.79 KB
/
refresh_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
package auth_manager
import (
"context"
"encoding/json"
"fmt"
"time"
)
const refreshTokenByteLength = 32
func generateHashKey(uuid string) string {
return fmt.Sprintf("refresh_token:%s", uuid)
}
type RefreshTokenPayload struct {
IPAddress string `json:"ipAddress"`
UserAgent string `json:"userAgent"`
LoggedInAt time.Duration `json:"loggedInAt"`
}
// The GenerateToken method generates a random string with base64 with a static byte length
// and stores it in the Redis store with provided expiration duration.
func (t *authManager) GenerateRefreshToken(ctx context.Context, uuid string, payload *RefreshTokenPayload, expiresAt time.Duration) (string, error) {
// Generate random string
refreshToken, err := generateRandomString(refreshTokenByteLength)
if err != nil {
return "", err
}
payloadJson, err := json.Marshal(payload)
if err != nil {
return "", ErrEncodingPayload
}
err = t.redisClient.HSet(ctx, generateHashKey(uuid), []string{
refreshToken, string(payloadJson),
}).Err()
if err != nil {
return "", err
}
return refreshToken, nil
}
func (t *authManager) DecodeRefreshToken(ctx context.Context, uuid string, token string) (*RefreshTokenPayload, error) {
payloadStr, err := t.redisClient.HGet(ctx, generateHashKey(uuid), token).Result()
if err != nil {
return nil, ErrInvalidToken
}
var payload *RefreshTokenPayload
err = json.Unmarshal([]byte(payloadStr), &payload)
if err != nil {
return nil, ErrInvalidToken
}
return payload, nil
}
func (t *authManager) TerminateRefreshTokens(ctx context.Context, uuid string) error {
return t.redisClient.Del(ctx, generateHashKey(uuid)).Err()
}
func (t *authManager) RemoveRefreshToken(ctx context.Context, uuid string, token string) error {
return t.redisClient.HDel(ctx, generateHashKey(uuid), token).Err()
}