-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xorm.go
219 lines (189 loc) · 4.96 KB
/
xorm.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
package oauth2xorm
import (
"fmt"
"encoding/json"
"time"
"os"
"io"
"github.com/go-xorm/xorm"
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/models"
_ "github.com/mattn/go-sqlite3"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
)
var noUpdateContent = "No content found to be updated"
// StoreItem data item
type StoreItem struct {
ID int64 `xorm:"pk autoincr"`
ExpiredAt int64
Code string `xorm:"varchar(512)"`
Access string `xorm:"varchar(512)"`
Refresh string `xorm:"varchar(512)"`
Data string `xorm:"text"`
}
// NewConfig create mysql configuration instance
func NewConfig(dsn string, dbType string, tableName string) *Config {
return &Config{
DSN: dsn,
DBType: dbType,
TableName: tableName,
MaxLifetime: time.Hour * 2,
}
}
// Config xorm configuration
type Config struct {
DSN string
DBType string
TableName string
MaxLifetime time.Duration
}
// NewStore create mysql store instance,
func NewStore(config *Config, gcInterval int) *Store {
x, err := xorm.NewEngine(config.DBType, config.DSN)
if err != nil {
panic(err)
}
return NewStoreWithDB(config, x, gcInterval)
}
func NewStoreWithDB(config *Config, x *xorm.Engine, gcInterval int) *Store {
store := &Store{
db: x,
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))
// TODO: create table if not exist
err := x.Sync2(new(StoreItem))
if err != nil {
panic(err)
}
go store.gc()
return store
}
// Store mysql token store
type Store struct {
tableName string
db *xorm.Engine
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()
counts, err := s.db.Where("expired_at > ?", now).Count(&StoreItem{})
if err != nil {
s.errorf("[ERROR]:%s\n", err.Error())
return
} else if counts > 0 {
_, err = s.db.Where("expired_at > ?", now).Delete(&StoreItem{})
if err != nil {
s.errorf("[ERROR]:%s\n", err.Error())
}
}
}
}
// Create create and store the new token information
func (s *Store) Create(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()
}
}
_, err = s.db.InsertOne(item)
return err
}
// RemoveByCode delete the authorization code
func (s *Store) RemoveByCode(code string) error {
_, err := s.db.Where("code = ?", code).Cols("code").Update(&StoreItem{Code:""})
return err
}
// RemoveByAccess use the access token to delete the token information
func (s *Store) RemoveByAccess(access string) error {
_, err := s.db.Where("access = ?", access).Cols("access").Update(&StoreItem{Access:""})
return err
}
// RemoveByRefresh use the refresh token to delete the token information
func (s *Store) RemoveByRefresh(refresh string) error {
_, err := s.db.Where("refresh = ?", refresh).Cols("refresh").Update(&StoreItem{Refresh:""})
return err
}
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(code string) (oauth2.TokenInfo, error) {
if code == "" {
return nil, nil
}
var item StoreItem
_, err := s.db.Where("code = ?", code).Get(&item)
if err != nil {
return nil, err
}
return s.toTokenInfo(item.Data), nil
}
// GetByAccess use the access token for token information data
func (s *Store) GetByAccess(access string) (oauth2.TokenInfo, error) {
if access == "" {
return nil, nil
}
var item StoreItem
_, err := s.db.Where("access = ?", access).Get(&item)
if err != nil {
return nil, err
}
return s.toTokenInfo(item.Data), nil
}
// GetByRefresh use the refresh token for token information data
func (s *Store) GetByRefresh(refresh string) (oauth2.TokenInfo, error) {
if refresh == "" {
return nil, nil
}
var item StoreItem
_, err := s.db.Where("refresh = ?", refresh).Get(&item)
if err != nil {
return nil, err
}
return s.toTokenInfo(item.Data), nil
}