forked from techknowlogick/go-oauth2-gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorm.go
295 lines (259 loc) · 6.47 KB
/
gorm.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package oauth2gorm
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
"github.com/go-oauth2/oauth2/v4"
"github.com/go-oauth2/oauth2/v4/models"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/driver/sqlserver"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// StoreItem data item
type StoreItem struct {
gorm.Model
ExpiredAt int64
Code string `gorm:"type:varchar(512)"`
Access string `gorm:"type:varchar(512)"`
Refresh string `gorm:"type:varchar(512)"`
Data string `gorm:"type:text"`
}
// NewConfig create mysql configuration instance
func NewConfig(dsn string, dbType DBType, tableName string) *Config {
return &Config{
DSN: dsn,
DBType: dbType,
TableName: tableName,
MaxLifetime: time.Hour * 2,
}
}
// Config gorm configuration
type Config struct {
DSN string
DBType DBType
TableName string
MaxLifetime time.Duration
}
type DBType int8
const (
MySQL = iota
PostgreSQL
SQLite
SQLServer
)
var defaultConfig = &gorm.Config{
Logger: logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // slow SQL
LogLevel: logger.Info, // log level
Colorful: true, // color
},
),
}
// NewStore create mysql store instance,
func NewStore(config *Config, gcInterval int) *Store {
var d gorm.Dialector
switch config.DBType {
case MySQL:
d = mysql.New(mysql.Config{
DSN: config.DSN,
})
case PostgreSQL:
d = postgres.New(postgres.Config{
DSN: config.DSN,
})
case SQLite:
d = sqlite.Open(config.DSN)
case SQLServer:
d = sqlserver.Open(config.DSN)
default:
fmt.Println("unsupported databases")
return nil
}
db, err := gorm.Open(d, defaultConfig)
if err != nil {
panic(err)
}
// default client pool
s, err := db.DB()
if err != nil {
panic(err)
}
s.SetMaxIdleConns(10)
s.SetMaxOpenConns(100)
s.SetConnMaxLifetime(time.Hour)
return NewStoreWithDB(config, db, gcInterval)
}
func NewStoreWithDB(config *Config, db *gorm.DB, gcInterval int) *Store {
store := &Store{
db: db,
tableName: "oauth2_token",
stdout: os.Stderr,
}
if config.TableName != "" {
store.tableName = config.TableName
}
interval := 600
if gcInterval > 0 {
interval = gcInterval
}
store.ticker = time.NewTicker(time.Second * time.Duration(interval))
if !db.Migrator().HasTable(store.tableName) {
if err := db.Table(store.tableName).Migrator().CreateTable(&StoreItem{}); err != nil {
panic(err)
}
}
go store.gc()
return store
}
// Store mysql token store
type Store struct {
tableName string
db *gorm.DB
stdout io.Writer
ticker *time.Ticker
}
// SetStdout set error output
func (s *Store) SetStdout(stdout io.Writer) *Store {
s.stdout = stdout
return s
}
// Close close the store
func (s *Store) Close() {
s.ticker.Stop()
}
func (s *Store) errorf(format string, args ...interface{}) {
if s.stdout != nil {
buf := fmt.Sprintf(format, args...)
s.stdout.Write([]byte(buf))
}
}
func (s *Store) gc() {
for range s.ticker.C {
now := time.Now().Unix()
var count int64
if err := s.db.Table(s.tableName).Where("expired_at <= ?", now).Or("code = ? and access = ? AND refresh = ?", "", "", "").Count(&count).Error; err != nil {
s.errorf("[ERROR]:%s\n", err)
return
}
if count > 0 {
// not soft delete.
if err := s.db.Table(s.tableName).Where("expired_at <= ?", now).Or("code = ? and access = ? AND refresh = ?", "", "", "").Unscoped().Delete(&StoreItem{}).Error; err != nil {
s.errorf("[ERROR]:%s\n", err)
}
}
}
}
// Create create and store the new token information
func (s *Store) Create(ctx context.Context, info oauth2.TokenInfo) error {
jv, err := json.Marshal(info)
if err != nil {
return err
}
item := &StoreItem{
Data: string(jv),
}
if code := info.GetCode(); code != "" {
item.Code = code
item.ExpiredAt = info.GetCodeCreateAt().Add(info.GetCodeExpiresIn()).Unix()
} else {
item.Access = info.GetAccess()
item.ExpiredAt = info.GetAccessCreateAt().Add(info.GetAccessExpiresIn()).Unix()
if refresh := info.GetRefresh(); refresh != "" {
item.Refresh = info.GetRefresh()
item.ExpiredAt = info.GetRefreshCreateAt().Add(info.GetRefreshExpiresIn()).Unix()
}
}
return s.db.WithContext(ctx).Table(s.tableName).Create(item).Error
}
// RemoveByCode delete the authorization code
func (s *Store) RemoveByCode(ctx context.Context, code string) error {
return s.db.WithContext(ctx).
Table(s.tableName).
Where("code = ?", code).
Update("code", "").
Error
}
// RemoveByAccess use the access token to delete the token information
func (s *Store) RemoveByAccess(ctx context.Context, access string) error {
return s.db.WithContext(ctx).
Table(s.tableName).
Where("access = ?", access).
Update("access", "").
Error
}
// RemoveByRefresh use the refresh token to delete the token information
func (s *Store) RemoveByRefresh(ctx context.Context, refresh string) error {
return s.db.WithContext(ctx).
Table(s.tableName).
Where("refresh = ?", refresh).
Update("refresh", "").
Error
}
func (s *Store) toTokenInfo(data string) oauth2.TokenInfo {
var tm models.Token
err := json.Unmarshal([]byte(data), &tm)
if err != nil {
return nil
}
return &tm
}
// GetByCode use the authorization code for token information data
func (s *Store) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) {
if code == "" {
return nil, nil
}
var item StoreItem
if err := s.db.WithContext(ctx).
Table(s.tableName).
Where("code = ?", code).
Find(&item).Error; err != nil {
return nil, err
}
if item.ID == 0 {
return nil, nil
}
return s.toTokenInfo(item.Data), nil
}
// GetByAccess use the access token for token information data
func (s *Store) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) {
if access == "" {
return nil, nil
}
var item StoreItem
if err := s.db.WithContext(ctx).
Table(s.tableName).
Where("access = ?", access).
Find(&item).Error; err != nil {
return nil, err
}
if item.ID == 0 {
return nil, nil
}
return s.toTokenInfo(item.Data), nil
}
// GetByRefresh use the refresh token for token information data
func (s *Store) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) {
if refresh == "" {
return nil, nil
}
var item StoreItem
if err := s.db.WithContext(ctx).
Table(s.tableName).
Where("refresh = ?", refresh).
Find(&item).Error; err != nil {
return nil, err
}
if item.ID == 0 {
return nil, nil
}
return s.toTokenInfo(item.Data), nil
}