/
store_redis.go
76 lines (64 loc) · 1.63 KB
/
store_redis.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
package oauthsession
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/appredis"
"github.com/authgear/authgear-server/pkg/util/duration"
)
const ttl = duration.UserInteraction + duration.Consent
type StoreRedis struct {
Context context.Context
Redis *appredis.Handle
AppID config.AppID
}
func (s *StoreRedis) Save(entry *Entry) (err error) {
jsonBytes, err := json.Marshal(entry)
if err != nil {
return
}
key := oauthSessionEntryKey(s.AppID, entry.ID)
err = s.Redis.WithConn(func(conn *goredis.Conn) error {
_, err := conn.Set(s.Context, key, jsonBytes, ttl).Result()
return err
})
if err != nil {
return
}
return
}
func (s *StoreRedis) Get(entryID string) (entry *Entry, err error) {
key := oauthSessionEntryKey(s.AppID, entryID)
err = s.Redis.WithConn(func(conn *goredis.Conn) error {
data, err := conn.Get(s.Context, key).Bytes()
if errors.Is(err, goredis.Nil) {
return ErrNotFound
} else if err != nil {
return err
}
var out Entry
err = json.Unmarshal(data, &out)
if err != nil {
return err
}
entry = &out
return nil
})
return
}
func (s *StoreRedis) Delete(entryID string) (err error) {
key := oauthSessionEntryKey(s.AppID, entryID)
return s.Redis.WithConn(func(conn *goredis.Conn) error {
_, err := conn.Del(s.Context, key).Result()
if err != nil {
return err
}
return err
})
}
func oauthSessionEntryKey(appID config.AppID, entryID string) string {
return fmt.Sprintf("app:%s:oauth-session-entry:%s", appID, entryID)
}