-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth2.js
466 lines (442 loc) · 15.2 KB
/
oauth2.js
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
'use strict'
// Register supported grant types.
//
// OAuth 2.0 specifies a framework that allows users to grant client
// applications limited access to their protected resources. It does this
// through a process of the user granting access, and the client exchanging the
// grant for an access token.
const config = require('./config')
const db = require('./db')
const User = require('./db/users')
const Client = require('./db/clients')
const login = require('connect-ensure-login')
const oauth2orize = require('oauth2orize')
const passport = require('passport')
const { createToken, logAndThrow } = require('./utils')
const validate = require('./validate')
// var changeHeaderAuthSecret = require('./authHeader');
// create OAuth 2.0 server
const server = oauth2orize.createServer()
// var oauth2orizeFacebook = require('oauth2orize-facebook');
var oauth2orizeFacebook = require('./oauth2orize-facebook')
var oauth2orizeGoogle = require('./oauth2orize-google')
// Configured expiresIn
const expiresIn = {
expires_in: config.token.expiresIn,
}
/**
* Grant authorization codes
*
* The callback takes the `client` requesting authorization, the `redirectURI`
* (which is used as a verifier in the subsequent exchange), the authenticated
* `user` granting access, and their response, which contains approved scope,
* duration, etc. as parsed by the application. The application issues a code,
* which is bound to these values, and will be exchanged for an access token.
*/
server.grant(
oauth2orize.grant.code((client, redirectURI, user, ares, done) => {
const code = createToken({
sub: user.username,
aud: client.name,
name: user.username,
role: user.role,
exp: config.codeToken.expiresIn,
})
db.authorizationCodes
.save(code, client.id, redirectURI, user.id, client.scope)
.then(() => done(null, code))
.catch((err) => done(err))
})
)
/**
* Grant implicit authorization.
*
* The callback takes the `client` requesting authorization, the authenticated
* `user` granting access, and their response, which contains approved scope,
* duration, etc. as parsed by the application. The application issues a token,
* which is bound to these values.
*/
server.grant(
oauth2orize.grant.token((client, user, ares, done) => {
const scope = getScopes(user)
const token = createToken({
sub: user.username,
aud: client.name,
name: user.username,
scope,
role: user.role,
exp: config.token.expiresIn,
})
const expiration = config.token.calculateExpirationDate()
db.accessTokens
.save(token, expiration, user.id, client.id, client.scope)
.then(() => done(null, token, expiresIn))
.catch((err) => done(err))
})
)
/**
* Exchange authorization codes for access tokens.
*
* The callback accepts the `client`, which is exchanging `code` and any
* `redirectURI` from the authorization request for verification. If these values
* are validated, the application issues an access token on behalf of the user who
* authorized the code.
*/
server.exchange(
oauth2orize.exchange.code((client, code, redirectURI, done) => {
db.authorizationCodes
.delete(code)
.then((authCode) =>
validate.authCode(code, authCode, client, redirectURI)
)
.then((authCode) => validate.generateTokens(authCode))
.then((tokens) => {
if (tokens.length === 1) {
return done(null, tokens[0], null, expiresIn)
}
if (tokens.length === 2) {
return done(null, tokens[0], tokens[1], expiresIn)
}
throw new Error('Error exchanging auth code for tokens')
})
.catch(() => done(null, false))
})
)
/**
* Get scope (api priviledges) for a user role
*
*
*/
const getScopes = (user) => {
if (user.role === 'admin') return ['read', 'write', 'translate', 'admin']
else if (user.role === 'translator') return ['read', 'write', 'translate']
else return ['read', 'write']
}
/**
* Exchange user id and password for access tokens.
*
* The callback accepts the `client`, which is exchanging the user's name and password
* from the token request for verification. If these values are validated, the
* application issues an access token on behalf of the user who authorized the code.
*
* This should be use just by our app, other spa should use implicit grant
*/
server.exchange(
oauth2orize.exchange.password(
async (client, username, password, scope, done) => {
try {
// active: true for old users, otherwise it's set active by activate endpoint
const user = await User.findOneAndUpdate(
{ email: username.toLowerCase() },
{ lastLogin: new Date(), active: true }
)
console.log(user)
if (!user) return done(null, false)
if (!user.authenticate(password)) return done(null, false)
const scope = getScopes(user)
const tokens = await validate.generateTokens({
scope,
userID: user._id,
clientID: client.name,
targetLanguages: user.targetLanguages,
role: user.role,
})
if (tokens === false) {
return done(null, false)
}
if (tokens.length === 1) {
return done(null, tokens[0], null, expiresIn)
}
if (tokens.length === 2) {
return done(null, tokens[0], tokens[1], expiresIn)
}
throw new Error('Error exchanging password for tokens')
} catch (err) {
return done(err)
}
}
)
)
/**
* Exchange the client id and password/secret for an access token.
*
* The callback accepts the `client`, which is exchanging the client's id and
* password/secret from the token request for verification. If these values are validated, the
* application issues an access token on behalf of the client who authorized the code.
*/
server.exchange(
oauth2orize.exchange.clientCredentials((client, scope, done) => {
const token = createToken({
sub: client.name,
aud: client.name,
name: client.name,
role: 'app',
exp: config.token.expiresIn,
})
const expiration = config.token.calculateExpirationDate()
// Pass in a null for user id since there is no user when using this grant type
db.accessTokens
.save(token, expiration, null, client.id, scope)
.then(() => done(null, token, null, expiresIn))
.catch((err) => done(err))
})
)
/**
* Exchange the refresh token for an access token.
*
* The callback accepts the `client`, which is exchanging the client's id from the token
* request for verification. If this value is validated, the application issues an access
* token on behalf of the client who authorized the code
*/
server.exchange(
oauth2orize.exchange.refreshToken((client, refreshToken, scope, done) => {
db.refreshTokens
.find(refreshToken)
.then((foundRefreshToken) =>
validate.refreshToken(foundRefreshToken, refreshToken, client)
)
.then((foundRefreshToken) => validate.generateToken(foundRefreshToken))
.then((token) => done(null, token, null, expiresIn))
.catch(() => done(null, false))
})
)
server.exchange(
oauth2orizeFacebook(function (client, profile, scope, done) {
//if user does not exists we create it
const query = {
$or: [{ 'facebook.id': profile.id }, { email: profile.email }],
}
// const query = { "facebook.id": profile.id };
const update = {
lastLogin: new Date(),
'facebook.name': profile.name,
'facebook.id': profile.id,
'facebook.email': profile.email,
'facebook.picture': `https://graph.facebook.com/${profile.id}/picture?type=large`,
$setOnInsert: {
locale: profile.locale,
searchLanguage: profile.locale,
email: profile.email,
active: true,
name: profile.name,
pictureProvider: 'facebook',
},
}
const options = {
upsert: true,
new: true,
setDefaultsOnInsert: true,
}
User.findOneAndUpdate(query, update, options)
.then((user) => {
const scope = getScopes(user)
return validate.generateTokens({
scope,
userID: user._id,
targetLanguages: user.targetLanguages,
role: user.role,
clientID: client.name,
})
})
.then((tokens) => {
if (tokens === false) {
return done(null, false)
}
if (tokens.length === 1) {
return done(null, tokens[0], null, expiresIn)
}
if (tokens.length === 2) {
return done(null, tokens[0], tokens[1], expiresIn)
}
throw new Error('Error exchanging facebook authcode for tokens')
})
.catch((err) => {
console.log(err)
done(null, false)
})
})
)
var option = {
googleConfig: {},
}
server.exchange(
oauth2orizeGoogle(option, function (client, profile, scope, done) {
//if user does not exists we create it
const query = {
$or: [{ 'google.id': profile.sub }, { email: profile.email }],
}
const update = {
lastLogin: new Date(),
'google.name': profile.name,
'google.id': profile.sub,
'google.email': profile.email,
'google.picture': profile.picture,
$setOnInsert: {
locale: profile.locale,
searchLanguage: profile.locale,
email: profile.email,
active: true,
name: profile.name,
pictureProvider: 'google',
},
}
const options = { upsert: true, new: true, setDefaultsOnInsert: true }
User.findOneAndUpdate(query, update, options)
.then((user) => {
const scope = getScopes(user)
return validate.generateTokens({
scope,
role: user.role,
userID: user._id,
targetLanguages: user.targetLanguages,
clientID: client.name,
})
})
.then((tokens) => {
if (tokens === false) {
return done(null, false)
}
if (tokens.length === 1) {
return done(null, tokens[0], null, expiresIn)
}
if (tokens.length === 2) {
return done(null, tokens[0], tokens[1], expiresIn)
}
throw new Error('Error exchanging google authcode for tokens')
})
.catch((err) => {
console.log(err)
done(null, false)
})
})
)
/*
* User authorization endpoint
*
* `authorization` middleware accepts a `validate` callback which is
* responsible for validating the client making the authorization request. In
* doing so, is recommended that the `redirectURI` be checked against a
* registered value, although security requirements may vary accross
* implementations. Once validated, the `done` callback must be invoked with
* a `client` instance, as well as the `redirectURI` to which the user will be
* redirected after an authorization decision is obtained.
*
* This middleware simply initializes a new authorization transaction. It is
* the application's responsibility to authenticate the user and render a dialog
* to obtain their approval (displaying details about the client requesting
* authorization). We accomplish that here by routing through `ensureLoggedIn()`
* first, and rendering the `dialog` view.
*/
exports.authorization = [
login.ensureLoggedIn(),
server.authorization((clientID, redirectURI, scope, done) => {
Client.findOne({ clientId: clientID })
.then((client) => {
if (!client) logAndThrow(`Client with id ${clientId} not found`)
client.scope = scope
done(null, client, redirectURI)
})
// WARNING: For security purposes, it is highly advisable to check that
// redirectURI provided by the client matches one registered with the
// server. For simplicity, this example does not. You have been
// warned.
.catch((err) => done(err))
}),
(req, res, next) => {
// Render the decision dialog if the client isn't a trusted client
// TODO: Make a mechanism so that if this isn't a trusted client, the user can
// record that they have consented but also make a mechanism so that if the user
// revokes access to any of the clients then they will have to re-consent.
Client.findOne({ clientId: req.query.client_id })
.then((client) => {
if (
client != null &&
client.trustedClient &&
client.trustedClient === true
) {
// This is how we short call the decision like the dialog below does
server.decision(
{
loadTransaction: false,
},
(serverReq, callback) => {
callback(null, { allow: true })
}
)(req, res, next)
} else {
res.render('dialog', {
transactionID: req.oauth2.transactionID,
user: req.user,
client: req.oauth2.client,
})
}
})
.catch(() =>
res.render('dialog', {
transactionID: req.oauth2.transactionID,
user: req.user,
client: req.oauth2.client,
})
)
},
]
/**
* User decision endpoint
*
* `decision` middleware processes a user's decision to allow or deny access
* requested by a client application. Based on the grant type requested by the
* client, the above grant middleware configured above will be invoked to send
* a response.
*/
exports.decision = [login.ensureLoggedIn(), server.decision()]
/**
* Token endpoint
*
* `token` middleware handles client requests to exchange authorization grants
* for access tokens. Based on the grant type being exchanged, the above
* exchange middleware will be invoked to handle the request. Clients must
* authenticate when making requests to this endpoint.
*/
exports.token = [
(req, res, next) => {
const allow_origins = [
'http://localhost:3000',
'https://arasaac.org',
'https://www.arasaac.org',
'https://admin.arasaac.org',
'https://www.admin.arasaac.org',
'https://beta.arasaac.org',
'https://editor.swagger.io',
]
console.log(req.headers.origin, 'ORIGIN')
console.log(allow_origins, 'allow_origins')
if (allow_origins.includes(req.headers.origin)) next()
else res.status(401).json({ error: 'Only allowed for arasaac.org' })
},
// changeHeaderAuthSecret({ clientId: 'abc123', secretId: 'ttttt' }),
passport.authenticate(['basic', 'oauth2-client-password'], {
session: false,
}),
server.token(),
server.errorHandler(),
]
// Register serialialization and deserialization functions.
//
// When a client redirects a user to user authorization endpoint, an
// authorization transaction is initiated. To complete the transaction, the
// user must authenticate and approve the authorization request. Because this
// may involve multiple HTTPS request/response exchanges, the transaction is
// stored in the session.
//
// An application must supply serialization functions, which determine how the
// client object is serialized into the session. Typically this will be a
// simple matter of serializing the client's ID, and deserializing by finding
// the client by ID from the database.
server.serializeClient((client, done) => done(null, client.clientId))
server.deserializeClient((id, done) => {
Client.findOne({ clientId: id }, (err, client) => {
if (err) done(err)
if (!client) done(null, null)
done(null, client)
})
})