forked from nextauthjs/next-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
464 lines (428 loc) · 16.1 KB
/
index.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
'use strict'
const BodyParser = require('body-parser')
const Express = require('express')
const ExpressSession = require('express-session')
const lusca = require('lusca')
const passportStrategies = require('./src/passport-strategies')
const uuid = require('uuid/v4')
module.exports = (nextApp, {
bodyParser = true,
// Optional, allows you to set e.g. 'limit' (maximum request body size, default 100kb)
bodyParserJsonOptions = {},
bodyParserUrlEncodedOptions = { extended: true },
csrf = true,
// URL base path for authentication routes (optional).
// Note: The prefix value of '/auth' is currently hard coded in
// next-auth-client so you should not change this unless you also modify it.
pathPrefix = '/auth',
// Express Server (optional).
expressApp = null,
// Express Session (optional).
expressSession = ExpressSession,
// Secret used to encrypt session data on the server.
sessionSecret = 'change-me',
// Session store for express-session.
// Defaults to an in memory store, which is not recommended for production.
sessionStore = expressSession.MemoryStore(),
// Maximum Session Age in ms (optional, default is 7 days).
// The expiry time for a session is reset every time a user revisits the site
// or revalidates their session token - this is the maximum idle time value.
sessionMaxAge = 60000 * 60 * 24 * 7,
// Session Revalidation in X ms (optional, default is 60 seconds).
// Specifies how often a Single Page App should revalidate a session.
// Does not impact the session life on the server, but causes clients to
// refetch session info (even if it is in a local cache) after N seconds has
// elapsed since it was last checked so they always display state correctly.
// If set to 0 will revalidate a session before rendering every page.
sessionRevalidateAge = 60000,
// Forces the session to be saved back to the session store, even if
// the session was never modified during the request. Depending on your
// store this may be necessary, but it can also create race conditions where
// a client makes two parallel requests to your server and changes made to
// the session in one request may get overwritten when the other request ends,
// even if it made no changes (this behavior also depends on what store you're
// using). https://www.npmjs.com/package/express-session#resave
sessionResave = false,
// Force a session identifier cookie to be set on every response. The expire
// time is reset to the original maxAge, resetting the expiration time.
// Note When this option is set to true but the saveUninitialized option
// is set to false, the cookie will not be set on a response with an
// uninitialized session https://www.npmjs.com/package/express-session#rolling
sessionRolling = true,
// Forces a session that is "uninitialized" to be saved to the store.
// A session is uninitialized when it is new but not modified. Choosing false
// is useful for implementing login sessions, reducing server storage usage,
// or complying with laws that require permission before setting a cookie.
//
// Choosing false will also help with race conditions where a client makes
// multiple parallel requests without a session.
//
// Note that if the build in CSRF protection is enabled (the default) then
// sessions will ALWAYS be 'initialized' as it saves to the session.
// https://www.npmjs.com/package/express-session#saveuninitialized
sessionSaveUninitialized = false,
// Canonical URL of the server (optional, but recommended).
// e.g. 'http://localhost:3000' or 'https://www.example.com'
// Used in callbak URLs and email sign in links. It will be auto generated
// if not specified, which may cause problems if your site uses multiple
// aliases (e.g. 'example.com and 'www.examples.com').
serverUrl = null,
// If we are behind a proxy server and it says we are running SSL, trust it.
// All this does is make sure we use HTTPS for callback URLs and email links.
// You should never need to turn this off.
trustProxy = true,
// An array of oAuth Provider config blocks (optional).
providers = [],
// Port to start listening on
port = null,
// Functions for find, update, insert, serialize and deserialize methods.
// They should all return a Promise with resolve() or reject().
// find() should return resolve(null) if no matching user found.
functions = {
find: ({
id,
email,
emailToken,
provider // provider = { name: 'twitter', id: '123456' }
} = {}) => { Promise.resolve(user) },
update: (user, profile) => { Promise.resolve(user) },
insert: (user, profile) => { Promise.resolve(user) },
remove: (id) => { Promise.resolve(id) },
serialize: (user) => { Promise.resolve(id) },
deserialize: (id) => { Promise.resolve(user) },
session: null,
sendSignInEmail: null, /* ({
email = null,
url = null,
req = null
} = {}) => { Promise.resolve(true) }
*/
signIn: null /* ({
email = null,
password = null
} = {}) => { Promise.resolve(user) }
*/
}
} = {}) => {
if (typeof(functions) !== 'object') {
throw new Error('functions must be a an object')
}
if (expressApp === null) {
expressApp = Express()
}
// If an instance of nextApp was passed, let all requests to /_next/* pass
// to it *before* Express Session and other middleware is called.
if (nextApp) {
expressApp.all('/_next/*', (req, res) => {
let nextRequestHandler = nextApp.getRequestHandler()
return nextRequestHandler(req, res)
})
}
/*
* Set up body parsing, express sessions and add CSRF tokens.
*
* You can set bodyParser to false and pass an Express instance if you want
* to customise how you invoke Body Parser.
*/
if (bodyParser === true) {
expressApp.use(BodyParser.json(bodyParserJsonOptions))
expressApp.use(BodyParser.urlencoded(bodyParserUrlEncodedOptions))
}
expressApp.use(expressSession({
secret: sessionSecret,
store: sessionStore,
resave: sessionResave,
rolling: sessionRolling,
saveUninitialized: sessionSaveUninitialized,
cookie: {
httpOnly: true,
secure: 'auto',
maxAge: sessionMaxAge
}
}))
if (csrf === true) {
// If csrf is true (default) apply to all routes
expressApp.use(lusca.csrf())
} else if (csrf !== false) {
// If csrf is anything else (except false) then pass it as a config option
expressApp.use(lusca.csrf(csrf))
} // if csrf is explicitly set to false then doesn't apply CSRF at all
if (trustProxy === true) {
expressApp.set('trust proxy', 1)
}
/*
* With sessions configured we need to configure Passport and trigger
* passport.initialize() before we add any other routes.
*/
passportStrategies({
expressApp: expressApp,
serverUrl: serverUrl,
providers: providers,
functions: functions
})
/*
* Add route to get CSRF token via AJAX
*/
expressApp.get(`${pathPrefix}/csrf`, (req, res) => {
return res.json({
csrfToken: res.locals._csrf
})
})
/*
* Return session info to client
*
* Will be stored in local storage, so should not return sensitive data that
* could be captured in a Cross Site Scripting attack (i.e. so not the session
* token) – or anything you don't want users to see (like private IDs) but is
* is okay to return things like access tokens for acessing remote services.
*/
expressApp.get(`${pathPrefix}/session`, (req, res) => {
let session = {
maxAge: sessionMaxAge,
revalidateAge: sessionRevalidateAge,
csrfToken: res.locals._csrf
}
if (req.user)
session.user = req.user
if (functions.session)
session = functions.session(session, req)
return res.json(session)
})
// Server side function for returning list of accounts user has linked.
// Called when pages are rendered in on the server (instead of /auth/linked).
// Returns all accounts the user has linked (e.g. Twitter, Facebook, Google…)
expressApp.use((req, res, next) => {
req.linked = () => {
return new Promise((resolve, reject) => {
if (!req.user) return resolve({})
functions.serialize(req.user)
.then(id => {
if (!id) throw new Error("Unable to serialize user")
return functions.find({ id: id })
})
.then(user => {
if (!user) return resolve({})
let linkedAccounts = {}
providers.forEach(provider => {
linkedAccounts[provider.providerName] = (user[provider.providerName.toLowerCase()]) ? true : false
})
return resolve(linkedAccounts)
})
.catch(err => {
return reject(err)
})
})
}
next()
})
// Client side REST endpoint for returning list of accounts user has linked.
// Called when pages are rendered in the browser (instead of req.linked()).
// Returns all accounts the user has linked (e.g. Twitter, Facebook, Google…)
expressApp.get(`${pathPrefix}/linked`, (req, res) => {
if (!req.user) return res.json({})
// First get the User ID from the User, then look up the user details.
// Note: We don't use the User object in req.user directly as it is a
// a simplified set of properties set by functions.deserialize().
functions.serialize(req.user)
.then(id => {
return functions.find({ id: id })
})
.then(user => {
if (!user) return res.json({})
let linkedAccounts = {}
providers.forEach(provider => {
linkedAccounts[provider.providerName] = (user[provider.providerName.toLowerCase()]) ? true : false
})
return res.json(linkedAccounts)
})
.catch(err => {
return res.status(500).end()
})
})
/*
* Return list of configured oAuth Providers
*
* We define this both as a server side function and a RESTful endpoint so
* that it can be used rendering a page both server side and client side.
*/
// Server side function
expressApp.use((req, res, next) => {
req.providers = () => {
return new Promise((resolve, reject) => {
let configuredProviders = {}
providers.forEach(provider => {
configuredProviders[provider.providerName] = {
signin: (serverUrl || '') + `${pathPrefix}/oauth/${provider.providerName.toLowerCase()}`,
callback: (serverUrl || '') + `${pathPrefix}/oauth/${provider.providerName.toLowerCase()}/callback`
}
})
return resolve(configuredProviders)
})
}
next()
})
// RESTful endpoint
expressApp.get(`${pathPrefix}/providers`, (req, res) => {
return new Promise((resolve, reject) => {
let configuredProviders = {}
providers.forEach(provider => {
configuredProviders[provider.providerName] = {
signin: (serverUrl || '') + `${pathPrefix}/oauth/${provider.providerName.toLowerCase()}`,
callback: (serverUrl || '') + `${pathPrefix}/oauth/${provider.providerName.toLowerCase()}/callback`
}
})
return res.json(configuredProviders)
})
})
/*
* Enable /auth/signin routes if signIn() function is passed
*/
if (functions.signIn) {
expressApp.post(`${pathPrefix}/signin`, (req, res) => {
// Passes all supplied credentials to the signIn function
functions.signIn({
form: req.body,
req: req
})
.then(user => {
if (user) {
// If signIn() returns a user, sign in as them
req.logIn(user, (err) => {
if (err) return res.redirect(`${pathPrefix}/error?action=signin&type=credentials`)
if (req.xhr) {
// If AJAX request (from client with JS), return JSON response
return res.json({success: true})
} else {
// If normal form POST (from client without JS) return redirect
return res.redirect(`${pathPrefix}/callback?action=signin&service=credentials`)
}
})
} else {
// If no user object is returned, bounce back to the sign in page
return res.redirect(`${pathPrefix}`)
}
})
.catch(err => {
return res.redirect(`${pathPrefix}/error?action=signin&type=credentials`)
})
})
}
/*
* Enable /auth/email/signin routes if sendSignInEmail() function is passed
*/
if (functions.sendSignInEmail) {
/*
* Generate a one time use sign in link and email it to the user
*/
expressApp.post(`${pathPrefix}/email/signin`, (req, res) => {
const email = req.body.email || null
if (!email || email.trim() === '') {
res.redirect(`${pathPrefix}`)
}
const token = uuid()
const url = (serverUrl || `${req.protocol}://${req.headers.host}`) + `${pathPrefix}/email/signin/${token}`
// Create verification token save it to database
functions.find({ email: email })
.then(user => {
if (user) {
// If a user with that email address exists already, update token.
user.emailToken = token
return functions.update(user)
} else {
// If the user does not exist, create a new account with the token.
return functions.insert({
email: email,
emailToken: token
})
}
})
.then(user => {
functions.sendSignInEmail({
email: user.email,
url: url,
req: req
})
if (req.xhr) {
// If AJAX request (from client with JS), return JSON response
return res.json({success: true})
} else {
// If normal form POST (from client without JS) return redirect
return res.redirect(`${pathPrefix}/check-email?email=${email}`)
}
})
.catch(err => {
return res.redirect(`${pathPrefix}/error?action=signin&type=email&email=${email}`)
})
})
/*
* Verify token in callback URL for email sign in
*/
expressApp.get(`${pathPrefix}/email/signin/:token`, (req, res) => {
if (!req.params.token) {
return res.redirect(`${pathPrefix}/error?action=signin&type=token-missing`)
}
functions.find({ emailToken: req.params.token })
.then(user => {
if (user) {
// Delete current token so it cannot be used again
delete user.emailToken
// Mark email as verified now we know they have access to it
user.emailVerified = true
return functions.update(user, null, { delete: 'emailToken' })
} else {
return Promise.reject(new Error("Token not valid"))
}
})
.then(user => {
// If the user object is valid, sign the user in
req.logIn(user, (err) => {
if (err) return res.redirect(`${pathPrefix}/error?action=signin&type=token-invalid`)
if (req.xhr) {
// If AJAX request (from client with JS), return JSON response
return res.json({success: true})
} else {
// If normal form POST (from client without JS) return redirect
return res.redirect(`${pathPrefix}/callback?action=signin&service=email`)
}
})
})
.catch(err => {
return res.redirect(`${pathPrefix}/error?action=signin&type=token-invalid`)
})
})
}
/*
* Sign a user out
*/
expressApp.post(`${pathPrefix}/signout`, (req, res) => {
// Log user out with Passport and remove their Express session
req.logout()
req.session.destroy(() => {
return res.redirect(`${pathPrefix}/callback?action=signout`)
})
})
return new Promise((resolve, reject) => {
let response = {
next: nextApp,
express: Express,
expressApp: expressApp,
functions: functions,
providers: providers,
port: port
}
// If no port specified, don't start Express automatically
if (!port) return resolve(response)
// If an instance of nextApp was passed, have it handle all other routes
if (nextApp) {
expressApp.all('*', (req, res) => {
let nextRequestHandler = nextApp.getRequestHandler()
return nextRequestHandler(req, res)
})
}
// Start Express
return expressApp.listen(port, err => {
if (err) reject(err)
return resolve(response)
})
})
}