/
token.go
400 lines (374 loc) · 9.94 KB
/
token.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
package dynamodb
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"gopkg.in/mgo.v2/bson"
"gopkg.in/oauth2.v3"
"gopkg.in/oauth2.v3/models"
)
// TokenConfig token configuration parameters
type TokenConfig struct {
// store token based data collection name(The default is oauth2_basic)
BasicCName string
// store access token data collection name(The default is oauth2_access)
AccessCName string
// store refresh token data collection name(The default is oauth2_refresh)
RefreshCName string
}
// TokenStore stores the dynamodb client and token config
type TokenStore struct {
tcfg *TokenConfig
client *dynamodb.DynamoDB
}
type basicData struct {
ID string `bson:"_id"`
Data []byte `bson:"Data"`
ExpiredAt time.Time `bson:"ExpiredAt"`
}
type tokenData struct {
ID string `bson:"_id"`
BasicID string `bson:"BasicID"`
ExpiredAt time.Time `bson:"ExpiredAt"`
}
func initTokenTable(client *dynamodb.DynamoDB, tokenConfig *TokenConfig) (err error) {
// Create authorization code table
input := &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("ID"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("ID"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(10),
WriteCapacityUnits: aws.Int64(10),
},
TableName: &tokenConfig.BasicCName,
}
_, err = client.CreateTable(input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case dynamodb.ErrCodeResourceInUseException:
break
default:
fmt.Println("Got error calling CreateTable for authorization code:")
fmt.Println(awsErr.Error())
os.Exit(1)
}
}
}
// Create access token table
input = &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("ID"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("ID"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(10),
WriteCapacityUnits: aws.Int64(10),
},
TableName: &tokenConfig.AccessCName,
}
_, err = client.CreateTable(input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case dynamodb.ErrCodeResourceInUseException:
break
default:
fmt.Println("Got error calling CreateTable for access token:")
fmt.Println(awsErr.Error())
os.Exit(1)
}
}
}
// Create refresh token table
input = &dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("ID"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("ID"),
KeyType: aws.String("HASH"),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(10),
WriteCapacityUnits: aws.Int64(10),
},
TableName: &tokenConfig.RefreshCName,
}
_, err = client.CreateTable(input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case dynamodb.ErrCodeResourceInUseException:
break
default:
fmt.Println("Got error calling CreateTable for refresh token:")
fmt.Println(awsErr.Error())
os.Exit(1)
}
}
}
return
}
// NewTokenStore returns a new token store
func NewTokenStore(client *dynamodb.DynamoDB, tokenConfig *TokenConfig) (store *TokenStore) {
initTokenTable(client, tokenConfig)
store = &TokenStore{
tcfg: tokenConfig,
client: client,
}
return
}
// NewDefaultTokenConfig returns a default token config
func NewDefaultTokenConfig() (config *TokenConfig) {
config = &TokenConfig{
BasicCName: "oauth2_basic",
AccessCName: "oauth2_access",
RefreshCName: "oauth2_refresh",
}
return
}
// InsertAuthorizationCode inserts an authorization code into the basic table
func InsertAuthorizationCode(ts *TokenStore, code string, data []byte, expiresAt string) (err error) {
params := &dynamodb.PutItemInput{
TableName: aws.String(ts.tcfg.BasicCName),
Item: map[string]*dynamodb.AttributeValue{
"ID": &dynamodb.AttributeValue{
S: aws.String(code),
},
"Data": &dynamodb.AttributeValue{
B: data,
},
"ExpiredAt": &dynamodb.AttributeValue{
S: aws.String(expiresAt),
},
},
}
_, err = ts.client.PutItem(params)
return
}
// InsertAccessToken inserts an access code into the basic table
func InsertAccessToken(ts *TokenStore, token string, basicID string, expiresAt string) (err error) {
params := &dynamodb.PutItemInput{
TableName: aws.String(ts.tcfg.AccessCName),
Item: map[string]*dynamodb.AttributeValue{
"ID": &dynamodb.AttributeValue{
S: aws.String(token),
},
"BasicID": &dynamodb.AttributeValue{
S: aws.String(basicID),
},
"ExpiredAt": &dynamodb.AttributeValue{
S: aws.String(expiresAt),
},
},
}
_, err = ts.client.PutItem(params)
return
}
// InsertRefreshToken inserts an access code into the basic table
func InsertRefreshToken(ts *TokenStore, token string, basicID string, expiresAt string) (err error) {
refreshParams := &dynamodb.PutItemInput{
TableName: aws.String(ts.tcfg.RefreshCName),
Item: map[string]*dynamodb.AttributeValue{
"ID": &dynamodb.AttributeValue{
S: aws.String(token),
},
"BasicID": &dynamodb.AttributeValue{
S: aws.String(basicID),
},
"ExpiredAt": &dynamodb.AttributeValue{
S: aws.String(expiresAt),
},
},
}
_, err = ts.client.PutItem(refreshParams)
return
}
// Create creates
func (ts *TokenStore) Create(info oauth2.TokenInfo) (err error) {
data, err := json.Marshal(info)
if err != nil {
return
}
if code := info.GetCode(); code != "" {
// Code already exists, update basic table
exp := info.GetCodeCreateAt().Add(info.GetCodeExpiresIn()).Format(time.RFC3339)
err = InsertAuthorizationCode(ts, code, data, exp)
return
}
aexp := info.GetAccessCreateAt().Add(info.GetAccessExpiresIn())
rexp := aexp
if refresh := info.GetRefresh(); refresh != "" {
rexp = info.GetRefreshCreateAt().Add(info.GetRefreshExpiresIn())
if aexp.Second() > rexp.Second() {
aexp = rexp
}
}
id := bson.NewObjectId().Hex()
// Update basic table with new token
err = InsertAuthorizationCode(ts, id, data, rexp.Format(time.RFC3339))
if err != nil {
return
}
err = InsertAccessToken(ts, info.GetAccess(), id, aexp.Format(time.RFC3339))
if err != nil {
return
}
if refresh := info.GetRefresh(); refresh != "" {
err = InsertRefreshToken(ts, refresh, id, rexp.Format(time.RFC3339))
}
return
}
// RemoveByCode use the authorization code to delete the token information
func (ts *TokenStore) RemoveByCode(code string) (err error) {
input := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(code),
},
},
TableName: aws.String(ts.tcfg.BasicCName),
}
_, err = ts.client.DeleteItem(input)
if err != nil {
fmt.Printf("RemoveByCode error: %s\n", err.Error())
}
return
}
// RemoveByAccess use the access token to delete the token information
func (ts *TokenStore) RemoveByAccess(access string) (err error) {
input := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(access),
},
},
TableName: aws.String(ts.tcfg.AccessCName),
}
_, err = ts.client.DeleteItem(input)
if err != nil {
fmt.Printf("RemoveByAccess error: %s\n", err.Error())
}
return
}
// RemoveByRefresh use the refresh token to delete the token information
func (ts *TokenStore) RemoveByRefresh(refresh string) (err error) {
input := &dynamodb.DeleteItemInput{
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(refresh),
},
},
TableName: aws.String(ts.tcfg.RefreshCName),
}
_, err = ts.client.DeleteItem(input)
if err != nil {
fmt.Printf("RemoveByRefresh error: %s\n", err.Error())
}
return
}
func (ts *TokenStore) getData(basicID string) (ti oauth2.TokenInfo, err error) {
if len(basicID) == 0 {
return
}
input := &dynamodb.GetItemInput{
TableName: aws.String(ts.tcfg.BasicCName),
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(basicID),
},
},
}
result, err := ts.client.GetItem(input)
if err != nil {
return
}
if len(result.Item) == 0 {
return
}
var b basicData
err = dynamodbattribute.UnmarshalMap(result.Item, &b)
if err != nil {
return
}
var tm models.Token
err = json.Unmarshal(b.Data, &tm)
if err != nil {
return
}
ti = &tm
return
}
func (ts *TokenStore) getBasicID(cname, token string) (basicID string, err error) {
input := &dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(token),
},
},
TableName: aws.String(cname),
}
result, err := ts.client.GetItem(input)
if err != nil {
return
}
var td tokenData
err = dynamodbattribute.UnmarshalMap(result.Item, &td)
if err != nil {
return
}
basicID = td.BasicID
return
}
// GetByCode use the authorization code for token information data
func (ts *TokenStore) GetByCode(code string) (ti oauth2.TokenInfo, err error) {
ti, err = ts.getData(code)
return
}
// GetByAccess use the access token for token information data
func (ts *TokenStore) GetByAccess(access string) (ti oauth2.TokenInfo, err error) {
basicID, err := ts.getBasicID(ts.tcfg.AccessCName, access)
if err != nil && basicID == "" {
return
}
ti, err = ts.getData(basicID)
return
}
// GetByRefresh use the refresh token for token information data
func (ts *TokenStore) GetByRefresh(refresh string) (ti oauth2.TokenInfo, err error) {
basicID, err := ts.getBasicID(ts.tcfg.RefreshCName, refresh)
if err != nil && basicID == "" {
return
}
ti, err = ts.getData(basicID)
return
}