-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtoken_store.go
265 lines (227 loc) · 6.13 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package mysql
import (
"database/sql"
"fmt"
"log"
"time"
"github.com/jmoiron/sqlx"
jsoniter "github.com/json-iterator/go"
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/models"
)
type TokenStore struct {
db *sqlx.DB
tableName string
gcDisabled bool
gcInterval time.Duration
ticker *time.Ticker
initTableDisabled bool
maxLifetime time.Duration
maxOpenConns int
maxIdleConns int
}
// TokenStoreItem data item
type TokenStoreItem struct {
ID int64 `db:"id"`
CreatedAt time.Time `db:"created_at"`
ExpiredAt time.Time `db:"expired_at"`
Code string `db:"code"`
Access string `db:"access"`
Refresh string `db:"refresh"`
Data string `db:"data"`
}
// NewTokenStore creates PostgreSQL store instance
func NewTokenStore(db *sqlx.DB, options ...TokenStoreOption) (*TokenStore, error) {
store := &TokenStore{
db: db,
tableName: "oauth2_tokens",
gcInterval: 10 * time.Minute,
maxLifetime: time.Hour * 2,
maxOpenConns: 50,
maxIdleConns: 25,
}
for _, o := range options {
o(store)
}
var err error
if !store.initTableDisabled {
err = store.initTable()
}
if err != nil {
return store, err
}
if !store.gcDisabled {
store.ticker = time.NewTicker(store.gcInterval)
go store.gc()
}
store.db.SetMaxOpenConns(store.maxOpenConns)
store.db.SetMaxIdleConns(store.maxIdleConns)
store.db.SetConnMaxLifetime(store.maxLifetime)
return store, err
}
// Close close the store
func (s *TokenStore) Close() error {
if !s.gcDisabled {
s.ticker.Stop()
}
return nil
}
func (s *TokenStore) gc() {
for range s.ticker.C {
s.clean()
}
}
func (s *TokenStore) initTable() error {
query := fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
code VARCHAR(255),
access VARCHAR(255) NOT NULL,
refresh VARCHAR(255) NOT NULL,
data TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expired_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
KEY access_k(access),
KEY refresh_k (refresh),
KEY expired_at_k (expired_at),
KEY code_k (code)
);
`, s.tableName)
stmt, err := s.db.Prepare(query)
if err != nil {
return err
}
_, err = stmt.Exec()
if err != nil {
return err
}
return nil
}
func (s *TokenStore) clean() {
now := time.Now().Unix()
query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE expired_at<=? OR (code='' AND access='' AND refresh='')", s.tableName)
var count int64
err := s.db.QueryRow(query, now).Scan(&count)
if err != nil || count == 0 {
if err != nil {
log.Println(err.Error())
}
return
}
_, err = s.db.Exec(fmt.Sprintf("DELETE FROM %s WHERE expired_at<=? OR (code='' AND access='' AND refresh='')", s.tableName), now)
if err != nil {
log.Println(err.Error())
}
}
// Create create and store the new token information
func (s *TokenStore) Create(info oauth2.TokenInfo) error {
buf, _ := jsoniter.Marshal(info)
item := &TokenStoreItem{
Data: string(buf),
CreatedAt: time.Now(),
}
if code := info.GetCode(); code != "" {
item.Code = code
item.ExpiredAt = info.GetCodeCreateAt().Add(info.GetCodeExpiresIn())
} else {
item.Access = info.GetAccess()
item.ExpiredAt = info.GetAccessCreateAt().Add(info.GetAccessExpiresIn())
if refresh := info.GetRefresh(); refresh != "" {
item.Refresh = info.GetRefresh()
item.ExpiredAt = info.GetRefreshCreateAt().Add(info.GetRefreshExpiresIn())
}
}
fmt.Print(item.CreatedAt)
_, err := s.db.Exec(
fmt.Sprintf("INSERT INTO %s (created_at, expired_at, code, access, refresh, data) VALUES (?,?,?,?,?,?)", s.tableName),
item.CreatedAt,
item.ExpiredAt,
item.Code,
item.Access,
item.Refresh,
item.Data)
if err != nil {
return err
}
return nil
}
// RemoveByCode delete the authorization code
func (s *TokenStore) RemoveByCode(code string) error {
query := fmt.Sprintf("DELETE FROM %s WHERE code=? LIMIT 1", s.tableName)
_, err := s.db.Exec(query, code)
if err != nil && err == sql.ErrNoRows {
return nil
}
return err
}
// RemoveByAccess use the access token to delete the token information
func (s *TokenStore) RemoveByAccess(access string) error {
query := fmt.Sprintf("DELETE FROM %s WHERE access=? LIMIT 1", s.tableName)
_, err := s.db.Exec(query, access)
if err != nil && err == sql.ErrNoRows {
return nil
}
return err
}
// RemoveByRefresh use the refresh token to delete the token information
func (s *TokenStore) RemoveByRefresh(refresh string) error {
query := fmt.Sprintf("DELETE FROM %s WHERE refresh=? LIMIT 1", s.tableName)
_, err := s.db.Exec(query, refresh)
if err != nil && err == sql.ErrNoRows {
return nil
}
return err
}
func (s *TokenStore) toTokenInfo(data string) oauth2.TokenInfo {
var tm models.Token
jsoniter.Unmarshal([]byte(data), &tm)
return &tm
}
// GetByCode use the authorization code for token information data
func (s *TokenStore) GetByCode(code string) (oauth2.TokenInfo, error) {
if code == "" {
return nil, nil
}
query := fmt.Sprintf("SELECT * FROM %s WHERE code=? LIMIT 1", s.tableName)
var item TokenStoreItem
err := s.db.QueryRowx(query, code).StructScan(&item)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
}
return s.toTokenInfo(item.Data), nil
}
// GetByAccess use the access token for token information data
func (s *TokenStore) GetByAccess(access string) (oauth2.TokenInfo, error) {
if access == "" {
return nil, nil
}
query := fmt.Sprintf("SELECT * FROM %s WHERE access=? LIMIT 1", s.tableName)
var item TokenStoreItem
err := s.db.QueryRowx(query, access).StructScan(&item)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
}
return s.toTokenInfo(item.Data), nil
}
// GetByRefresh use the refresh token for token information data
func (s *TokenStore) GetByRefresh(refresh string) (oauth2.TokenInfo, error) {
if refresh == "" {
return nil, nil
}
query := fmt.Sprintf("SELECT * FROM %s WHERE refresh=? LIMIT 1", s.tableName)
var item TokenStoreItem
err := s.db.QueryRowx(query, refresh).StructScan(&item)
switch {
case err == sql.ErrNoRows:
return nil, nil
case err != nil:
return nil, err
}
return s.toTokenInfo(item.Data), nil
}