This repository has been archived by the owner on Mar 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathosindynamodb.go
601 lines (532 loc) · 15.1 KB
/
osindynamodb.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
package osindynamodb
import (
"encoding/json"
"errors"
"time"
"github.com/RangelReale/osin"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
var (
// ErrClientNotFound is returned by GetClient if client was not found
ErrClientNotFound = osin.ErrNotFound
// ErrAuthorizeNotFound is returned by LoadAuthorize if authorization code was not found
ErrAuthorizeNotFound = osin.ErrNotFound
// ErrAccessNotFound is returned by LoadAccess if access token was not found
ErrAccessNotFound = osin.ErrNotFound
// ErrRefreshNotFound is returned by LoadRefresh if refresh token was not found
ErrRefreshNotFound = osin.ErrNotFound
// ErrTokenExpired is returned by LoadAccess, LoadAuthorize or LoadRefresh if token or code expired
ErrTokenExpired = errors.New("Token expired")
)
// New returns a new DynamoDB storage instance.
func New(db *dynamodb.DynamoDB, config StorageConfig) *Storage {
return &Storage{
db: db,
config: config,
}
}
// Storage implements the storage interface for OSIN (https://github.com/RangelReale/osin)
// with Amazon DynamoDB (https://aws.amazon.com/dynamodb/)
// using aws-sdk-go (https://github.com/aws/aws-sdk-go).
type Storage struct {
db *dynamodb.DynamoDB
config StorageConfig
}
// StorageConfig allows to pass configuration to Storage on initialization
type StorageConfig struct {
// ClientTable is the name of table for clients
ClientTable string
// AuthorizeTable is the name of table for authorization codes
AuthorizeTable string
// AccessTable is the name of table for access tokens
AccessTable string
// RefreshTable is the name of table for refresh tokens
RefreshTable string
// CreateUserData is a function that allows you to create struct
// to which osin.AccessData.UserData will be json.Unmarshaled.
// Example:
// struct AppUserData{
// Username string
// }
// func() interface{} {
// return &AppUserData{}
// }
CreateUserData func() interface{}
}
// UserData is an interface that allows you to store UserData values
// as DynamoDB attributes in AccessTable and RefreshTable
type UserData interface {
// ToAttributeValues lists user data as attribute values for DynamoDB table
ToAttributeValues() map[string]*dynamodb.AttributeValue
}
// CreateSchema initiates db with basic schema layout
// This is not a part of interface but can be useful for initiating basic schema and for tests
func (receiver *Storage) CreateSchema() error {
createParams := []*dynamodb.CreateTableInput{
{
TableName: aws.String(receiver.config.AccessTable),
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("token"),
AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("token"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
},
{
TableName: aws.String(receiver.config.AuthorizeTable),
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("code"),
AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("code"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
},
{
TableName: aws.String(receiver.config.ClientTable),
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("id"),
AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("id"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
},
{
TableName: aws.String(receiver.config.RefreshTable),
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("token"),
AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("token"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
},
}
for i := range createParams {
if err := createTable(receiver.db, createParams[i]); err != nil {
return err
}
}
return nil
}
// DropSchema drops all tables
// This is not a part of interface but can be useful in tests
func (receiver *Storage) DropSchema() error {
tables := []string{
receiver.config.AccessTable,
receiver.config.AuthorizeTable,
receiver.config.RefreshTable,
receiver.config.ClientTable,
}
for i := range tables {
if err := deleteTable(receiver.db, tables[i]); err != nil {
return err
}
}
return nil
}
func createTable(db *dynamodb.DynamoDB, createParams *dynamodb.CreateTableInput) error {
_, err := db.CreateTable(createParams)
if err != nil {
return err
}
describeParams := &dynamodb.DescribeTableInput{
TableName: aws.String(*createParams.TableName),
}
if err := db.WaitUntilTableExists(describeParams); err != nil {
return err
}
return nil
}
func deleteTable(db *dynamodb.DynamoDB, tableName string) error {
params := &dynamodb.DeleteTableInput{
TableName: aws.String(tableName),
}
_, err := db.DeleteTable(params)
if err != nil {
return err
}
describeParams := &dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
}
if err := db.WaitUntilTableNotExists(describeParams); err != nil {
return err
}
return nil
}
// Clone the storage if needed. Has no effect with this library, it's only to satisfy interface.
func (receiver *Storage) Clone() osin.Storage {
return receiver
}
// Close the resources the Storage potentially holds. Has no effect with this library, it's only to satisfy interface.
func (receiver *Storage) Close() {
}
// CreateClient adds new client.
// This is not a part of interface and as so, it's never used in osin flow.
// However can be really usefull for applications to add new clients.
func (receiver *Storage) CreateClient(client osin.Client) error {
data, err := json.Marshal(client)
if err != nil {
return err
}
params := &dynamodb.PutItemInput{
Item: map[string]*dynamodb.AttributeValue{
"id": {
S: aws.String(client.GetId()),
},
"json": {
S: aws.String(string(data)),
},
},
TableName: aws.String(receiver.config.ClientTable),
}
if _, err := receiver.db.PutItem(params); err != nil {
return err
}
return nil
}
// GetClient loads the client by id (client_id)
func (receiver *Storage) GetClient(id string) (osin.Client, error) {
var client *osin.DefaultClient
params := &dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"id": {
S: aws.String(id),
},
},
ProjectionExpression: aws.String("id, json"),
TableName: aws.String(receiver.config.ClientTable),
}
resp, err := receiver.db.GetItem(params)
if err != nil {
return nil, err
}
if len(resp.Item) == 0 {
return nil, ErrClientNotFound
}
data := resp.Item["json"].S
err = json.Unmarshal([]byte(*data), &client)
if err != nil {
return nil, err
}
return client, nil
}
// RemoveClient revokes or deletes client.
// This is not a part of interface and as so, it's never used in osin flow.
// However can be really usefull for applications to remove or revoke clients.
func (receiver *Storage) RemoveClient(id string) error {
params := &dynamodb.DeleteItemInput{
TableName: aws.String(receiver.config.ClientTable),
Key: map[string]*dynamodb.AttributeValue{
"id": {
S: aws.String(id),
},
},
}
_, err := receiver.db.DeleteItem(params)
if err != nil {
return err
}
return nil
}
// SaveAuthorize saves authorize data.
func (receiver *Storage) SaveAuthorize(authorizeData *osin.AuthorizeData) error {
data, err := json.Marshal(authorizeData)
if err != nil {
return err
}
params := &dynamodb.PutItemInput{
Item: map[string]*dynamodb.AttributeValue{
"code": {
S: aws.String(authorizeData.Code),
},
"json": {
S: aws.String(string(data)),
},
},
TableName: aws.String(receiver.config.AuthorizeTable),
}
if _, err := receiver.db.PutItem(params); err != nil {
return err
}
return nil
}
// LoadAuthorize looks up AuthorizeData by a code.
// Client information is loaded together.
// Can return error if expired.
func (receiver *Storage) LoadAuthorize(code string) (authorizeData *osin.AuthorizeData, err error) {
params := &dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"code": {
S: aws.String(code),
},
},
ProjectionExpression: aws.String("json"),
TableName: aws.String(receiver.config.AuthorizeTable),
}
resp, err := receiver.db.GetItem(params)
if err != nil {
return nil, err
}
if len(resp.Item) == 0 {
return nil, ErrAuthorizeNotFound
}
authorizeData = &osin.AuthorizeData{}
authorizeData.Client = &osin.DefaultClient{}
data := resp.Item["json"].S
err = json.Unmarshal([]byte(*data), &authorizeData)
if err != nil {
return nil, err
}
if authorizeData.ExpireAt().Before(time.Now()) {
return nil, ErrTokenExpired
}
return authorizeData, nil
}
// RemoveAuthorize revokes or deletes the authorization code.
func (receiver *Storage) RemoveAuthorize(code string) error {
params := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"code": {
S: aws.String(code),
},
},
TableName: aws.String(receiver.config.AuthorizeTable),
}
if _, err := receiver.db.DeleteItem(params); err != nil {
return err
}
return nil
}
// SaveAccess writes AccessData.
func (receiver *Storage) SaveAccess(accessData *osin.AccessData) error {
// @issue https://github.com/RangelReale/osin/issues/47
if accessData.AccessData != nil && accessData.AccessData.AccessData != nil {
accessData.AccessData.AccessData = nil
}
data, err := json.Marshal(accessData)
if err != nil {
return err
}
items := map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(accessData.AccessToken),
},
"json": {
S: aws.String(string(data)),
},
}
if userData, ok := accessData.UserData.(UserData); ok {
for k, v := range userData.ToAttributeValues() {
items[k] = v
}
}
params := &dynamodb.PutItemInput{
Item: items,
TableName: aws.String(receiver.config.AccessTable),
}
if _, err := receiver.db.PutItem(params); err != nil {
return err
}
if accessData.RefreshToken != "" {
return receiver.SaveRefresh(accessData)
}
return nil
}
// LoadAccess retrieves access data by token. Client information is loaded together.
// Can return error if expired.
func (receiver *Storage) LoadAccess(token string) (accessData *osin.AccessData, err error) {
params := &dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(token),
},
},
ProjectionExpression: aws.String("json"),
TableName: aws.String(receiver.config.AccessTable),
}
resp, err := receiver.db.GetItem(params)
if err != nil {
return nil, err
}
if len(resp.Item) == 0 {
return nil, ErrAccessNotFound
}
accessData = &osin.AccessData{}
accessData.Client = &osin.DefaultClient{}
accessData.AccessData = &osin.AccessData{
Client: &osin.DefaultClient{},
AuthorizeData: &osin.AuthorizeData{
Client: &osin.DefaultClient{},
},
}
accessData.AuthorizeData = &osin.AuthorizeData{
Client: &osin.DefaultClient{},
}
if receiver.config.CreateUserData != nil {
accessData.UserData = receiver.config.CreateUserData()
}
data := resp.Item["json"].S
err = json.Unmarshal([]byte(*data), &accessData)
if err != nil {
return nil, err
}
if accessData.ExpireAt().Before(time.Now()) {
return nil, ErrTokenExpired
}
return accessData, nil
}
// RemoveAccess revokes or deletes an AccessData.
func (receiver *Storage) RemoveAccess(token string) error {
params := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(token),
},
},
TableName: aws.String(receiver.config.AccessTable),
}
if _, err := receiver.db.DeleteItem(params); err != nil {
return err
}
return nil
}
// SaveRefresh writes AccessData for refresh token
// This method is not a part of interface and as so, it's never used in osin flow.
// This method is used internally by SaveAccess(accessData *osin.AccessData)
// and can be useful for testing
func (receiver *Storage) SaveRefresh(accessData *osin.AccessData) error {
// @issue https://github.com/RangelReale/osin/issues/47
if accessData.AccessData != nil && accessData.AccessData.AccessData != nil {
accessData.AccessData.AccessData = nil
}
data, err := json.Marshal(accessData)
if err != nil {
return err
}
items := map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(accessData.RefreshToken),
},
"json": {
S: aws.String(string(data)),
},
}
if userData, ok := accessData.UserData.(UserData); ok {
for k, v := range userData.ToAttributeValues() {
items[k] = v
}
}
params := &dynamodb.PutItemInput{
Item: items,
TableName: aws.String(receiver.config.RefreshTable),
}
if _, err := receiver.db.PutItem(params); err != nil {
return err
}
return nil
}
// LoadRefresh retrieves refresh AccessData. Client information is loaded together.
// Refresh token doesn't expire.
func (receiver *Storage) LoadRefresh(token string) (accessData *osin.AccessData, err error) {
params := &dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(token),
},
},
ProjectionExpression: aws.String("json"),
TableName: aws.String(receiver.config.RefreshTable),
}
resp, err := receiver.db.GetItem(params)
if err != nil {
return nil, err
}
if len(resp.Item) == 0 {
return nil, ErrRefreshNotFound
}
accessData = &osin.AccessData{}
accessData.Client = &osin.DefaultClient{}
accessData.AccessData = &osin.AccessData{
Client: &osin.DefaultClient{},
AuthorizeData: &osin.AuthorizeData{
Client: &osin.DefaultClient{},
},
}
accessData.AuthorizeData = &osin.AuthorizeData{
Client: &osin.DefaultClient{},
}
if receiver.config.CreateUserData != nil {
accessData.UserData = receiver.config.CreateUserData()
}
data := resp.Item["json"].S
err = json.Unmarshal([]byte(*data), &accessData)
if err != nil {
return nil, err
}
return accessData, nil
}
// RemoveRefresh revokes or deletes refresh AccessData.
func (receiver *Storage) RemoveRefresh(token string) error {
params := &dynamodb.DeleteItemInput{
TableName: aws.String(receiver.config.RefreshTable),
Key: map[string]*dynamodb.AttributeValue{
"token": {
S: aws.String(token),
},
},
}
_, err := receiver.db.DeleteItem(params)
if err != nil {
return err
}
return nil
}
// CreateStorageConfig prefixes all table names and returns StorageConfig
func CreateStorageConfig(prefix string) StorageConfig {
return StorageConfig{
AccessTable: prefix + "access",
ClientTable: prefix + "client",
RefreshTable: prefix + "refresh",
AuthorizeTable: prefix + "authorize",
}
}