-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathetcd_session_store.go
83 lines (65 loc) · 1.49 KB
/
etcd_session_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
83
package casstore
import (
"context"
"fmt"
clientv3 "go.etcd.io/etcd/client/v3"
"gopkg.in/cas.v2"
)
var _ cas.SessionStore = &etcdSessionStore{}
// NewEtcdSessionStore create a session store using etcd.
func NewEtcdSessionStore(config clientv3.Config, ctx context.Context,
prefix string, maxAge int64) (cas.SessionStore, error) {
client, err := clientv3.New(config)
if err != nil {
return nil, err
}
if prefix == "" {
prefix = "/cas/sessions"
}
if maxAge == 0 {
maxAge = 86400
}
return &etcdSessionStore{
cli: client,
ctx: ctx,
prefix: prefix,
maxAge: maxAge,
}, nil
}
type etcdSessionStore struct {
cli *clientv3.Client
ctx context.Context
prefix string
maxAge int64
}
func (s *etcdSessionStore) Get(sessionID string) (string, bool) {
key := s.prefix + "/" + sessionID
resp, err := s.cli.Get(s.ctx, key)
if err != nil {
return "", false
}
if resp.Count == 0 {
return "", false
}
return string(resp.Kvs[0].Value), true
}
func (s *etcdSessionStore) Set(sessionID, ticket string) error {
key := s.prefix + "/" + sessionID
grant, err := s.cli.Grant(s.ctx, s.maxAge+1)
if err != nil {
return err
}
_, err = s.cli.Put(s.ctx, key, ticket, clientv3.WithLease(grant.ID))
return err
}
func (s *etcdSessionStore) Delete(sessionID string) error {
key := s.prefix + "/" + sessionID
resp, err := s.cli.Delete(s.ctx, key)
if err != nil {
return err
}
if resp.Deleted == 0 {
return fmt.Errorf("key: %s is not found in etcd", key)
}
return nil
}