-
Notifications
You must be signed in to change notification settings - Fork 26
/
mysql.go
363 lines (319 loc) · 11.3 KB
/
mysql.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Package mysql is a osin storage implementation for mysql.
package mysql
import (
"database/sql"
"fmt"
"log"
"strings"
"time"
"github.com/RangelReale/osin"
"github.com/ansel1/merry"
"github.com/felipeweb/gopher-utils"
// driver for mysql db
_ "github.com/go-sql-driver/mysql"
)
var schemas = []string{`CREATE TABLE IF NOT EXISTS {prefix}client (
id varchar(255) BINARY NOT NULL PRIMARY KEY,
secret varchar(255) NOT NULL,
extra varchar(255) NOT NULL,
redirect_uri varchar(255) NOT NULL
)`, `CREATE TABLE IF NOT EXISTS {prefix}authorize (
client varchar(255) BINARY NOT NULL,
code varchar(255) BINARY NOT NULL PRIMARY KEY,
expires_in int(10) NOT NULL,
scope varchar(255) NOT NULL,
redirect_uri varchar(255) NOT NULL,
state varchar(255) NOT NULL,
extra varchar(255) NOT NULL,
created_at timestamp NOT NULL
)`, `CREATE TABLE IF NOT EXISTS {prefix}access (
client varchar(255) BINARY NOT NULL,
authorize varchar(255) BINARY NOT NULL,
previous varchar(255) BINARY NOT NULL,
access_token varchar(255) BINARY NOT NULL PRIMARY KEY,
refresh_token varchar(255) BINARY NOT NULL,
expires_in int(10) NOT NULL,
scope varchar(255) NOT NULL,
redirect_uri varchar(255) NOT NULL,
extra varchar(255) NOT NULL,
created_at timestamp NOT NULL
)`, `CREATE TABLE IF NOT EXISTS {prefix}refresh (
token varchar(255) BINARY NOT NULL PRIMARY KEY,
access varchar(255) BINARY NOT NULL
)`, `CREATE TABLE IF NOT EXISTS {prefix}expires (
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
token varchar(255) BINARY NOT NULL,
expires_at timestamp NOT NULL,
INDEX expires_index (expires_at),
INDEX token_expires_index (token)
)`,
}
// Storage implements interface "github.com/RangelReale/osin".Storage and interface "github.com/felipeweb/osin-mysql/storage".Storage
type Storage struct {
db *sql.DB
tablePrefix string
}
// New returns a new mysql storage instance.
func New(db *sql.DB, tablePrefix string) *Storage {
return &Storage{db, tablePrefix}
}
// CreateSchemas creates the schemata, if they do not exist yet in the database. Returns an error if something went wrong.
func (s *Storage) CreateSchemas() error {
for k, schema := range schemas {
schema := strings.Replace(schema, "{prefix}", s.tablePrefix, 4)
if _, err := s.db.Exec(schema); err != nil {
log.Printf("Error creating schema %d: %s", k, schema)
return err
}
}
return nil
}
// Clone the storage if needed. For example, using mgo, you can clone the session with session.Clone
// to avoid concurrent access problems.
// This is to avoid cloning the connection at each method access.
// Can return itself if not a problem.
func (s *Storage) Clone() osin.Storage {
return s
}
// Close the resources the Storage potentially holds (using Clone for example)
func (s *Storage) Close() {
}
// GetClient loads the client by id
func (s *Storage) GetClient(id string) (osin.Client, error) {
row := s.db.QueryRow(fmt.Sprintf("SELECT id, secret, redirect_uri, extra FROM %sclient WHERE id=?", s.tablePrefix), id)
var c osin.DefaultClient
var extra string
if err := row.Scan(&c.Id, &c.Secret, &c.RedirectUri, &extra); err == sql.ErrNoRows {
return nil, osin.ErrNotFound
} else if err != nil {
return nil, merry.Wrap(err)
}
c.UserData = extra
return &c, nil
}
// UpdateClient updates the client (identified by it's id) and replaces the values with the values of client.
func (s *Storage) UpdateClient(c osin.Client) error {
data := gopher_utils.ToStr(c.GetUserData())
if _, err := s.db.Exec(fmt.Sprintf("UPDATE %sclient SET secret=?, redirect_uri=?, extra=? WHERE id=?", s.tablePrefix), c.GetSecret(), c.GetRedirectUri(), data, c.GetId()); err != nil {
return merry.Wrap(err)
}
return nil
}
// CreateClient stores the client in the database and returns an error, if something went wrong.
func (s *Storage) CreateClient(c osin.Client) error {
data := gopher_utils.ToStr(c.GetUserData())
if _, err := s.db.Exec(fmt.Sprintf("INSERT INTO %sclient (id, secret, redirect_uri, extra) VALUES (?, ?, ?, ?)", s.tablePrefix), c.GetId(), c.GetSecret(), c.GetRedirectUri(), data); err != nil {
return merry.Wrap(err)
}
return nil
}
// RemoveClient removes a client (identified by id) from the database. Returns an error if something went wrong.
func (s *Storage) RemoveClient(id string) (err error) {
if _, err = s.db.Exec(fmt.Sprintf("DELETE FROM %sclient WHERE id=?", s.tablePrefix), id); err != nil {
return merry.Wrap(err)
}
return nil
}
// SaveAuthorize saves authorize data.
func (s *Storage) SaveAuthorize(data *osin.AuthorizeData) (err error) {
extra := gopher_utils.ToStr(data.UserData)
if err != nil {
return err
}
if _, err = s.db.Exec(
fmt.Sprintf("INSERT INTO %sauthorize (client, code, expires_in, scope, redirect_uri, state, created_at, extra) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", s.tablePrefix),
data.Client.GetId(),
data.Code,
data.ExpiresIn,
data.Scope,
data.RedirectUri,
data.State,
data.CreatedAt,
extra,
); err != nil {
return merry.Wrap(err)
}
if err = s.AddExpireAtData(data.Code, data.ExpireAt()); err != nil {
return merry.Wrap(err)
}
return nil
}
// LoadAuthorize looks up AuthorizeData by a code.
// Client information MUST be loaded together.
// Optionally can return error if expired.
func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
var data osin.AuthorizeData
var extra string
var cid string
if err := s.db.QueryRow(fmt.Sprintf("SELECT client, code, expires_in, scope, redirect_uri, state, created_at, extra FROM %sauthorize WHERE code=? LIMIT 1", s.tablePrefix), code).Scan(&cid, &data.Code, &data.ExpiresIn, &data.Scope, &data.RedirectUri, &data.State, &data.CreatedAt, &extra); err == sql.ErrNoRows {
return nil, osin.ErrNotFound
} else if err != nil {
return nil, merry.Wrap(err)
}
data.UserData = extra
c, err := s.GetClient(cid)
if err != nil {
return nil, err
}
if data.ExpireAt().Before(time.Now()) {
return nil, merry.Errorf("Token expired at %s.", data.ExpireAt().String())
}
data.Client = c
return &data, nil
}
// RemoveAuthorize revokes or deletes the authorization code.
func (s *Storage) RemoveAuthorize(code string) (err error) {
if _, err = s.db.Exec(fmt.Sprintf("DELETE FROM %sauthorize WHERE code=?", s.tablePrefix), code); err != nil {
return merry.Wrap(err)
}
if err = s.RemoveExpireAtData(code); err != nil {
return merry.Wrap(err)
}
return nil
}
// SaveAccess writes AccessData.
// If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.
func (s *Storage) SaveAccess(data *osin.AccessData) (err error) {
prev := ""
authorizeData := &osin.AuthorizeData{}
if data.AccessData != nil {
prev = data.AccessData.AccessToken
}
if data.AuthorizeData != nil {
authorizeData = data.AuthorizeData
}
extra := gopher_utils.ToStr(data.UserData)
tx, err := s.db.Begin()
if err != nil {
return merry.Wrap(err)
}
if data.RefreshToken != "" {
if err := s.saveRefresh(tx, data.RefreshToken, data.AccessToken); err != nil {
return err
}
}
if data.Client == nil {
return merry.New("data.Client must not be nil")
}
_, err = tx.Exec(fmt.Sprintf("INSERT INTO %saccess (client, authorize, previous, access_token, refresh_token, expires_in, scope, redirect_uri, created_at, extra) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", s.tablePrefix), data.Client.GetId(), authorizeData.Code, prev, data.AccessToken, data.RefreshToken, data.ExpiresIn, data.Scope, data.RedirectUri, data.CreatedAt, extra)
if err != nil {
if rbe := tx.Rollback(); rbe != nil {
return merry.Wrap(rbe)
}
return merry.Wrap(err)
}
if err = s.AddExpireAtData(data.AccessToken, data.ExpireAt()); err != nil {
return merry.Wrap(err)
}
if err = tx.Commit(); err != nil {
return merry.Wrap(err)
}
return nil
}
// LoadAccess retrieves access data by token. Client information MUST be loaded together.
// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (s *Storage) LoadAccess(code string) (*osin.AccessData, error) {
var extra, cid, prevAccessToken, authorizeCode string
var result osin.AccessData
if err := s.db.QueryRow(
fmt.Sprintf("SELECT client, authorize, previous, access_token, refresh_token, expires_in, scope, redirect_uri, created_at, extra FROM %saccess WHERE access_token=? LIMIT 1", s.tablePrefix),
code,
).Scan(
&cid,
&authorizeCode,
&prevAccessToken,
&result.AccessToken,
&result.RefreshToken,
&result.ExpiresIn,
&result.Scope,
&result.RedirectUri,
&result.CreatedAt,
&extra,
); err == sql.ErrNoRows {
return nil, osin.ErrNotFound
} else if err != nil {
return nil, merry.Wrap(err)
}
result.UserData = extra
client, err := s.GetClient(cid)
if err != nil {
return nil, err
}
result.Client = client
result.AuthorizeData, _ = s.LoadAuthorize(authorizeCode)
prevAccess, _ := s.LoadAccess(prevAccessToken)
result.AccessData = prevAccess
return &result, nil
}
// RemoveAccess revokes or deletes an AccessData.
func (s *Storage) RemoveAccess(code string) (err error) {
if _, err = s.db.Exec(fmt.Sprintf("DELETE FROM %saccess WHERE access_token=?", s.tablePrefix), code); err != nil {
return merry.Wrap(err)
}
if err = s.RemoveExpireAtData(code); err != nil {
return merry.Wrap(err)
}
return nil
}
// LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together.
// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (s *Storage) LoadRefresh(code string) (*osin.AccessData, error) {
row := s.db.QueryRow(fmt.Sprintf("SELECT access FROM %srefresh WHERE token=? LIMIT 1", s.tablePrefix), code)
var access string
if err := row.Scan(&access); err == sql.ErrNoRows {
return nil, osin.ErrNotFound
} else if err != nil {
return nil, merry.Wrap(err)
}
return s.LoadAccess(access)
}
// RemoveRefresh revokes or deletes refresh AccessData.
func (s *Storage) RemoveRefresh(code string) error {
_, err := s.db.Exec(fmt.Sprintf("DELETE FROM %srefresh WHERE token=?", s.tablePrefix), code)
if err != nil {
return merry.Wrap(err)
}
return nil
}
// CreateClientWithInformation Makes easy to create a osin.DefaultClient
func (s *Storage) CreateClientWithInformation(id string, secret string, redirectURI string, userData interface{}) osin.Client {
return &osin.DefaultClient{
Id: id,
Secret: secret,
RedirectUri: redirectURI,
UserData: userData,
}
}
func (s *Storage) saveRefresh(tx *sql.Tx, refresh, access string) (err error) {
_, err = tx.Exec(fmt.Sprintf("INSERT INTO %srefresh (token, access) VALUES (?, ?)", s.tablePrefix), refresh, access)
if err != nil {
if rbe := tx.Rollback(); rbe != nil {
return merry.Wrap(rbe)
}
return merry.Wrap(err)
}
return nil
}
// AddExpireAtData add info in expires table
func (s *Storage) AddExpireAtData(code string, expireAt time.Time) error {
if _, err := s.db.Exec(
fmt.Sprintf("INSERT INTO %sexpires(token, expires_at) VALUES(?, ?)", s.tablePrefix),
code,
expireAt,
); err != nil {
return merry.Wrap(err)
}
return nil
}
// RemoveExpireAtData remove info in expires table
func (s *Storage) RemoveExpireAtData(code string) error {
if _, err := s.db.Exec(
fmt.Sprintf("DELETE FROM %sexpires WHERE token=?", s.tablePrefix),
code,
); err != nil {
return merry.Wrap(err)
}
return nil
}