forked from nerdzeu/nerdz-api
/
oauth2.go
358 lines (296 loc) · 10.8 KB
/
oauth2.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
/*
Copyright (C) 2016 Paolo Galeone <nessuno@nerdz.eu>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nerdz
import (
"database/sql"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/RangelReale/osin"
"github.com/nerdzeu/nerdz-api/utils"
)
// isValidScope checks if scope is a valid scope
func (s *OAuth2Storage) isValidScope(scope string) error {
scopes := strings.Split(scope, " ")
for _, s := range scopes {
parts := strings.Split(s, ":")
if len(parts) != 2 {
return errors.New("Scope (" + s + ") has invalid format. The valid format is: scope:[read,write]")
}
if !utils.InSlice(parts[0], Configuration.Scopes) {
return errors.New("Requested scope (" + s + ") does not exist")
}
rw := strings.Split(parts[1], ",")
for _, permission := range rw {
if permission != "read" && permission != "write" {
return errors.New("Invalid permission: " + permission + ". Allowed: read,write")
}
}
}
return nil
}
// OAuth2Storage implements osin.Storage interface
type OAuth2Storage struct {
}
// 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 *OAuth2Storage) Clone() osin.Storage {
return s
}
// Close the resources the Storage potentially holds (using Clone for example)
func (s *OAuth2Storage) Close() {
}
// GetClient loads the client by id (client_id)
func (s *OAuth2Storage) GetClient(id string) (osin.Client, error) {
var err error
var numericID uint64
if numericID, err = strconv.ParseUint(id, 10, 64); err != nil {
return nil, fmt.Errorf("invalid client_id: %s", id)
}
client := new(OAuth2Client)
err = Db().First(client, numericID)
return client, err
}
// SaveAuthorize saves authorize data.
func (s *OAuth2Storage) SaveAuthorize(data *osin.AuthorizeData) error {
var clientID uint64
var err error
if clientID, err = strconv.ParseUint(data.Client.GetId(), 10, 64); err != nil {
return err
}
if err = s.isValidScope(data.Scope); err != nil {
return fmt.Errorf("Saving Authorize: " + err.Error())
}
d := &OAuth2AuthorizeData{
ClientID: clientID,
Code: data.Code,
// CreatedAt field is automatically filled by the dbms
ExpiresIn: uint64(data.ExpiresIn),
RedirectURI: data.RedirectUri,
Scope: data.Scope,
//State: data.State,
UserID: data.UserData.(uint64)}
return Db().Create(d)
}
// LoadAuthorize looks up osin.AuthorizeData by a code.
// osin.Client information MUST be loaded together.
// Optionally can return error if expired.
func (s *OAuth2Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
authorize := new(OAuth2AuthorizeData)
e := Db().Model(OAuth2AuthorizeData{}).Where(&OAuth2AuthorizeData{Code: code}).Scan(authorize)
if e != nil {
return nil, e
}
if code != authorize.Code {
return nil, errors.New("Authorization data not found")
}
authData := &osin.AuthorizeData{
Code: code,
CreatedAt: authorize.CreatedAt.Round(time.Second),
ExpiresIn: int32(authorize.ExpiresIn),
RedirectUri: authorize.RedirectURI,
Scope: authorize.Scope,
//State: authorize.State,
UserData: authorize.UserID}
if authData.IsExpired() {
return nil, errors.New("Authorization data expired")
}
if client, err := s.GetClient(strconv.FormatUint(authorize.ClientID, 10)); err == nil {
authData.Client = client
return authData, nil
}
return nil, errors.New("LoadAuthorize: Client not found")
}
// RemoveAuthorize revokes or deletes the authorization code.
func (s *OAuth2Storage) RemoveAuthorize(code string) error {
return Db().Where(&OAuth2AuthorizeData{Code: code}).Delete(OAuth2AuthorizeData{})
}
// SaveAccess writes osin.AccessData.
// If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.
func (s *OAuth2Storage) SaveAccess(accessData *osin.AccessData) error {
var clientID uint64
var err error
if clientID, err = strconv.ParseUint(accessData.Client.GetId(), 10, 64); err != nil {
return errors.New("Invalid Client ID")
}
if err = s.isValidScope(accessData.Scope); err != nil {
return fmt.Errorf("Saving Access: " + err.Error())
}
var accessDataIDPtr sql.NullInt64
if accessData.AccessData != nil {
var father OAuth2AccessData
if err = Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{AccessToken: accessData.AccessData.AccessToken}).Scan(&father); err != nil {
return errors.New("Error fetching parent Access Data ID")
}
accessDataIDPtr.Int64, accessDataIDPtr.Valid = int64(father.ID), true
}
// required to fill the foreign key
var authorizeDataIDPtr sql.NullInt64
if accessData.AuthorizeData != nil {
var authorizeData OAuth2AuthorizeData
if err = Db().Model(OAuth2AuthorizeData{}).Where(&OAuth2AuthorizeData{Code: accessData.AuthorizeData.Code}).Scan(&authorizeData); err != nil {
return fmt.Errorf("SaveAccess: can't load authorize data with code: %s", accessData.AuthorizeData.Code)
}
authorizeDataIDPtr.Int64, authorizeDataIDPtr.Valid = int64(authorizeData.ID), true
}
tx := Db().Begin()
var refreshTokenFK sql.NullInt64
oauthAccessData := &OAuth2AccessData{
AccessDataID: accessDataIDPtr,
AccessToken: accessData.AccessToken,
AuthorizeDataID: authorizeDataIDPtr,
ClientID: clientID,
//CreatedAt: accessData.CreatedAt, <- dbms handled
ExpiresIn: uint64(accessData.ExpiresIn),
RedirectURI: accessData.RedirectUri,
Scope: accessData.Scope,
UserID: accessData.UserData.(uint64)}
if accessData.RefreshToken != "" {
// Create refresh token
var newRefreshToken OAuth2RefreshToken
newRefreshToken.Token = accessData.RefreshToken
if err := tx.Create(&newRefreshToken); err != nil {
tx.Rollback()
return err
}
refreshTokenFK.Int64 = int64(newRefreshToken.ID)
refreshTokenFK.Valid = true
}
// Put refresh token id, into OAuth2AccessData.refreshtoken fk
oauthAccessData.RefreshTokenID = refreshTokenFK
if err := tx.Create(oauthAccessData); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
return nil
}
// LoadAccess retrieves access data by token. osin.Client information MUST be loaded together.
// osin.AuthorizeData and osin.AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (s *OAuth2Storage) LoadAccess(token string) (*osin.AccessData, error) {
oad := new(OAuth2AccessData)
if err := Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{AccessToken: token}).Scan(oad); err != nil {
return nil, errors.New("LoadAccess: AccessToken not found")
}
var ret osin.AccessData
ret.CreatedAt = oad.CreatedAt
ret.ExpiresIn = int32(oad.ExpiresIn)
if ret.IsExpired() {
return nil, errors.New("Access token expired")
}
if client, err := s.GetClient(strconv.FormatUint(oad.ClientID, 10)); err == nil {
ret.Client = client
} else {
return nil, err
}
ret.AccessToken = token
ret.Scope = oad.Scope
ret.RedirectUri = oad.RedirectURI
ret.UserData = oad.UserID
if oad.RefreshTokenID.Valid {
var refreshToken OAuth2RefreshToken
if err := Db().First(&refreshToken, uint64(oad.RefreshTokenID.Int64)); err != nil {
return nil, err
}
ret.RefreshToken = refreshToken.Token
}
return &ret, nil
}
// RemoveAccess revokes or deletes an osin.AccessData.
func (s *OAuth2Storage) RemoveAccess(token string) error {
return Db().Where(&OAuth2AccessData{AccessToken: token}).Delete(OAuth2AccessData{})
}
// LoadRefresh retrieves refresh osin.AccessData. osin.Client information MUST be loaded together.
// osin.AuthorizeData and osin.AccessData DON'T NEED to be loaded if not easily available.
// Optionally can return error if expired.
func (s *OAuth2Storage) LoadRefresh(token string) (*osin.AccessData, error) {
var pointedAccessData OAuth2AccessData
var refreshToken OAuth2RefreshToken
if err := Db().Model(OAuth2RefreshToken{}).Where(&OAuth2RefreshToken{Token: token}).Scan(&refreshToken); err != nil || refreshToken.Token == "" {
return nil, errors.New("Refresh token not found")
}
var refreshTokenNullInt64 sql.NullInt64
refreshTokenNullInt64.Int64, refreshTokenNullInt64.Valid = int64(refreshToken.ID), true
if err := Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{RefreshTokenID: refreshTokenNullInt64}).Scan(&pointedAccessData); err != nil {
return nil, err
}
return s.LoadAccess(pointedAccessData.AccessToken)
}
// RemoveRefresh revokes or deletes refresh osin.AccessData.
func (s *OAuth2Storage) RemoveRefresh(token string) error {
return Db().Where(&OAuth2RefreshToken{Token: token}).Delete(OAuth2RefreshToken{})
}
// Implementing the osin.Client interface
// GetId returns the client ID
func (d *OAuth2Client) GetId() string {
return strconv.FormatUint(d.ID, 10)
}
// GetSecret returns the client secret
func (d *OAuth2Client) GetSecret() string {
return d.Secret
}
// GetRedirectUri returns the client redirect URI
func (d *OAuth2Client) GetRedirectUri() string {
return d.RedirectURI
}
// GetUserData returns client UserData
func (d *OAuth2Client) GetUserData() interface{} {
return d.UserID
}
// Additional methods
// RemoveClient removes the client by id (primary key)
func (s *OAuth2Storage) RemoveClient(id uint64) error {
if id <= 0 {
return errors.New("Invalid client id")
}
return Db().Where(&OAuth2Client{ID: id}).Delete(OAuth2Client{})
}
// CreateClient creates a new OAuth2 Client
func (s *OAuth2Storage) CreateClient(c osin.Client, name string) (*OAuth2Client, error) {
client := OAuth2Client{
Name: name,
RedirectURI: c.GetRedirectUri(),
Secret: c.GetSecret(),
UserID: c.GetUserData().(uint64),
}
if err := Db().Create(&client); err != nil {
return nil, err
}
return &client, nil
}
// UpdateClient update client with id c.GetId()
func (s *OAuth2Storage) UpdateClient(c osin.Client) (*OAuth2Client, error) {
var numericID uint64
var err error
if numericID, err = strconv.ParseUint(c.GetId(), 10, 64); err != nil {
return nil, fmt.Errorf("invalid client_id: %s", c.GetId())
}
client := OAuth2Client{
ID: numericID,
RedirectURI: c.GetRedirectUri(),
Secret: c.GetSecret(),
UserID: c.GetUserData().(uint64),
}
if err := Db().Updates(&client); err != nil {
return nil, err
}
return &client, nil
}