-
Notifications
You must be signed in to change notification settings - Fork 1
/
plain_token.go
53 lines (42 loc) · 1.19 KB
/
plain_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
package auth_manager
import (
"context"
"encoding/json"
"time"
)
// Used for ResetPassword, VerifyEmail, SessionBasedAuthentication, etc.
func (t *authManager) GeneratePlainToken(ctx context.Context, tokenType TokenType, payload *TokenPayload, expiresAt time.Duration) (string, error) {
token, err := generateRandomString(TokenByteLength)
if err != nil {
return "", err
}
claimsJson, err := json.Marshal(&payload)
if err != nil {
return "", err
}
cmd := t.redisClient.Set(ctx, token, claimsJson, expiresAt)
if cmd.Err() != nil {
return "", cmd.Err()
}
return token, nil
}
func (t *authManager) DecodePlainToken(ctx context.Context, token string, tokenType TokenType) (*TokenPayload, error) {
claimsString, err := t.redisClient.Get(ctx, token).Result()
if err != nil {
return nil, err
}
claims := &TokenPayload{}
err = json.Unmarshal([]byte(claimsString), &claims)
if err != nil {
return nil, ErrInvalidToken
}
return claims, nil
}
// The Destroy method is simply used to remove a key from Redis Store.
func (t *authManager) DestroyPlainToken(ctx context.Context, key string) error {
cmd := t.redisClient.Del(ctx, key)
if cmd.Err() != nil {
return cmd.Err()
}
return nil
}