-
Notifications
You must be signed in to change notification settings - Fork 28
/
token_store.go
82 lines (68 loc) · 1.63 KB
/
token_store.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
package appsecret
import (
"context"
"encoding/json"
"errors"
"fmt"
goredis "github.com/go-redis/redis/v8"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/lib/infra/redis/globalredis"
"github.com/authgear/authgear-server/pkg/util/duration"
)
type AppSecretVisitTokenStoreImpl struct {
Context context.Context
Redis *globalredis.Handle
}
const Lifetime = duration.Short
func (s *AppSecretVisitTokenStoreImpl) CreateToken(
appID config.AppID,
userID string,
secrets []config.SecretKey,
) (*AppSecretVisitToken, error) {
token := NewAppSecretVisitToken(
userID,
secrets,
)
bytes, err := json.Marshal(token)
if err != nil {
return nil, err
}
err = s.Redis.WithConn(func(conn *goredis.Conn) error {
key := redisTokenKey(appID, token.TokenID)
ttl := Lifetime
_, err := conn.SetEX(s.Context, key, bytes, ttl).Result()
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return token, nil
}
func (s *AppSecretVisitTokenStoreImpl) GetTokenByID(
appID config.AppID,
tokenID string,
) (*AppSecretVisitToken, error) {
key := redisTokenKey(appID, tokenID)
var token AppSecretVisitToken
err := s.Redis.WithConn(func(conn *goredis.Conn) error {
bytes, err := conn.Get(s.Context, key).Bytes()
if errors.Is(err, goredis.Nil) {
return ErrTokenNotFound
}
if err != nil {
return err
}
err = json.Unmarshal(bytes, &token)
if err != nil {
return err
}
return nil
})
return &token, err
}
func redisTokenKey(appID config.AppID, tokenID string) string {
return fmt.Sprintf("app:%s:secret-visit-token:%s", appID, tokenID)
}