-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
578 lines (555 loc) · 21.9 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
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
const fs = require('fs');
const path = require('path');
const humanname = require('humanname');
const { AuthTokenRefresh } = require('passport-oauth2-refresh');
module.exports = {
bundle: {
directory: 'modules',
modules: getBundleModuleNames()
},
async init(self) {
await self.enablePassportStrategies();
},
options: {
i18n: {
ns: 'aposPassportBridge'
}
},
methods(self) {
return {
async enablePassportStrategies() {
self.refresh = new AuthTokenRefresh();
self.strategies = {};
if (!self.apos.baseUrl) {
throw new Error('@apostrophecms/passport-bridge: you must configure the top-level "baseUrl" option for apostrophe');
}
if (!Array.isArray(self.options.strategies)) {
throw new Error('@apostrophecms/passport-bridge: you must configure the "strategies" option');
}
for (const spec of self.options.strategies) {
// Works with npm modules that export the strategy directly, npm modules
// that export a Strategy property, and directly passing in a strategy property
// in the spec
const strategyModule = spec.module && await self.apos.root.import(spec.module);
const Strategy = strategyModule
? (strategyModule.Strategy || strategyModule)
: spec.Strategy;
if (!Strategy) {
throw new Error('@apostrophecms/passport-bridge: each strategy must have a "module" setting\n' +
'giving the name of an npm module installed in your project that\n' +
'is passport-oauth2, passport-oauth or a subclass with a compatible\n' +
'interface, such as passport-gitlab2, passport-twitter, etc.\n\n' +
'You may instead pass a strategy constructor as a Strategy property,\n' +
'but the other way is much more convenient.');
}
// Are there strategies requiring no options? Probably not, but maybe...
spec.options = spec.options || {};
const scope = spec.options.scope || spec?.authenticate?.scope;
spec.options.scope = spec?.authenticate?.scope;
spec.authenticate = spec.authenticate || {};
spec.authenticate.scope = spec.authenticate.scope || scope;
if (!spec.name) {
// It's hard to find the strategy name; it's not the same
// as the npm name. And we need it to build the callback URL
// sensibly. But we can do it by making a dummy strategy object now
const dummy = new Strategy({
callbackURL: 'https://dummy/test',
passReqToCallback: true,
...spec.options
}, self.findOrCreateUser(spec));
spec.name = dummy.name;
}
spec.label = spec.label || spec.name;
spec.options.callbackURL = self.getCallbackUrl(spec, true);
self.strategies[spec.name] = new Strategy({
passReqToCallback: true,
...spec.options
}, self.findOrCreateUser(spec));
self.apos.login.passport.use(self.strategies[spec.name]);
self.refresh.use(self.strategies[spec.name]);
};
},
// Returns the oauth2 callback URL, which must match the route
// established by `addCallbackRoute`. If `absolute` is true
// then `baseUrl` and `apos.prefix` are prepended, otherwise
// not (because `app.get` automatically prepends a prefix).
// If the callback URL was preconfigured via spec.options.callbackURL
// it is returned as-is when `absolute` is true, otherwise
// the pathname is returned with any `apos.prefix` removed
// to avoid adding it twice in `app.get` calls.
getCallbackUrl(spec, absolute) {
let url;
if (spec.options && spec.options.callbackURL) {
url = spec.options.callbackURL;
if (absolute) {
return url;
}
const parsed = new URL(url);
url = parsed.pathname;
if (self.apos.prefix) {
// Remove the prefix if present, so that app.get doesn't
// add it redundantly
return url.replace(new RegExp('^' + self.apos.util.regExpQuote(self.apos.prefix)), '');
}
return parsed.pathname;
}
return (absolute ? (self.apos.baseUrl + self.apos.prefix) : '') + '/auth/' + spec.name + '/callback';
},
// Returns the URL you should link users to in order for them
// to log in. If `absolute` is true then `baseUrl` and `apos.prefix`
// are prepended, otherwise not (because `app.get` automatically prepends a prefix).
getLoginUrl(spec, absolute) {
return (absolute ? (self.apos.baseUrl + self.apos.prefix) : '') + '/auth/' + spec.name + '/login';
},
// Returns the URL used to confirm a connection to another service.
// Since this is used in email `absolute` is usually `true`, however
// it is also used to create routes.
getConnectUrl(strategyName, token, absolute) {
return (absolute ? (self.apos.baseUrl + self.apos.prefix) : '') + '/auth/' + strategyName + '/connect/' + token;
},
// Adds the login route
// which will be `/auth/strategyname/login`, where the strategy name
// depends on the passport module being used.
//
// Redirect users to this URL
// to start the process of logging them in via each strategy
addLoginRoute(spec) {
self.apos.app.get(self.getLoginUrl(spec), (req, res, next) => {
if (req.query.newLocale) {
req.session.passportLocale = {
oldLocale: req.query.oldLocale,
newLocale: req.query.newLocale,
oldAposDocId: req.query.oldAposDocId
};
return res.redirect(self.apos.url.build(req.url, {
newLocale: null,
oldLocale: null,
oldAposDocId: null
}));
} else {
return next();
}
}, self.apos.login.passport.authenticate(spec.name, spec.authenticate));
},
addConnectRoute(spec) {
self.apos.app.get(self.getConnectUrl(spec.name, ':token'), async (req, res) => {
const strategyName = spec.name;
try {
const token = req.params.token;
if (!token.length) {
self.apos.util.info('No token provided to connect route');
return res.redirect(self.getFailureUrl(spec));
}
const safe = await self.apos.user.safe.findOne({
[`connectionRequests.${strategyName}.token`]: token
});
if (!safe) {
self.apos.util.info('Token not found for connect route');
return res.redirect(self.getFailureUrl(spec));
}
const request = safe.connectionRequests[strategyName];
if (request.expiresAt < Date.now()) {
self.apos.util.info('Token expired for connect route');
return res.redirect(self.getFailureUrl(spec));
}
const nonce = self.apos.util.generateId();
await self.apos.user.safe.updateOne({
_id: safe._id
}, {
$set: {
[`connectionRequests.${strategyName}`]: {
nonce,
session: {
...req.session
}
}
}
});
res.cookie('apos-connect', `${strategyName}:${nonce}`, {
maxAge: 1000 * 60 * 60 * 24,
httpOnly: true,
secure: (req.protocol === 'https')
});
return res.redirect(self.getLoginUrl(spec));
} catch (e) {
self.apos.util.error(e);
return res.redirect(self.getFailureUrl(spec));
}
});
},
// Adds the callback route associated with a strategy. oauth-based strategies and
// certain others redirect here to complete the login handshake
addCallbackRoute(spec) {
self.apos.app.get(self.getCallbackUrl(spec, false),
// middleware
self.apos.login.passport.authenticate(
spec.name,
{
...spec.authenticate,
failureRedirect: self.getFailureUrl(spec)
}
),
// The actual route reached after authentication redirects
// appropriately, either to an explicitly requested location
// or the home page
(req, res) => {
const redirect = req.session.passportRedirect || '/';
delete req.session.passportRedirect;
return res.rawRedirect(redirect);
}
);
},
addFailureRoute(spec) {
self.apos.app.get(self.getFailureUrl(spec), function (req, res) {
// Gets i18n'd in the template
return self.sendPage(req, 'error', {
spec,
message: 'aposPassportBridge:rejected'
});
});
},
getFailureUrl(spec) {
return '/auth/' + spec.name + '/error';
},
// Given a strategy spec from the configuration, return
// an oauth passport callback function to find the user based
// on the profile, creating them if appropriate.
findOrCreateUser(spec) {
return body;
async function body(req, accessToken, refreshToken, profile, callback) {
if (!req?.res) {
// req was not passed (strategy used does not support that), shift
// parameters by one so they come in under the right names
return body(null, req, accessToken, refreshToken, profile);
}
// Always use an admin req to find the user
const adminReq = self.apos.task.getReq();
let criteria = {};
if (spec.accept) {
if (!spec.accept(profile)) {
return callback(null, false);
}
}
const connectingUserId = req && await self.getConnectingUserId(req, spec.name);
if (connectingUserId) {
criteria._id = connectingUserId;
} else {
const emails = self.getRelevantEmailsFromProfile(spec, profile);
if (spec.emailDomain && (!emails.length)) {
// Email domain filter is in effect and user has no emails or
// only emails in the wrong domain
return callback(null, false);
}
if (typeof (spec.match) === 'function') {
criteria = spec.match(profile);
} else {
switch (spec.match || 'username') {
case 'id':
if (!profile.id) {
self.apos.util.error('@apostrophecms/passport-bridge: profile has no id. You probably want to set the "match" option for this strategy to "username" or "email".');
return callback(null, false);
}
criteria[spec.name + 'Id'] = profile.id;
break;
case 'username':
if (!profile.username) {
self.apos.util.error('@apostrophecms/passport-bridge: profile has no username. You probably want to set the "match" option for this strategy to "id" or "email".');
return callback(null, false);
}
criteria.username = profile.username;
break;
case 'email':
case 'emails':
if (!emails.length) {
// User has no email
return callback(null, false);
}
criteria.$or = emails.map(email => {
return { email };
});
break;
default:
return callback(new Error(`@apostrophecms/passport-bridge: ${spec.match} is not a supported value for the match property`));
}
}
}
criteria.disabled = { $ne: true };
if ((!connectingUserId) && (spec.login === false)) {
// Some strategies are only for connecting, not logging in
return callback(null, false);
}
try {
const user = await self.apos.user.find(adminReq, criteria).toObject() ||
(
self.options.create &&
!connectingUserId &&
await self.createUser(spec, profile)
);
// Legacy, incompatible with Passport 0.6
if (self.options.retainAccessTokenInSession && user && req) {
req.session.accessToken = accessToken;
req.session.refreshToken = refreshToken;
}
// Preferred, see documentation
if (self.options.retainAccessToken && user) {
await self.apos.user.safe.updateOne({
_id: user._id
}, {
$set: {
[`tokens.${spec.name}.accessToken`]: accessToken,
[`tokens.${spec.name}.refreshToken`]: refreshToken
}
});
}
if (user) {
await self.apos.doc.db.updateOne({
_id: user._id
}, {
$set: {
[`${spec.name}Id`]: profile.id
}
});
}
return callback(null, user || false);
} catch (err) {
self.apos.util.error(err);
return callback(err);
}
};
},
async getConnectingUserId(req, strategyName) {
const info = await self.getConnectingInfo(req);
if (strategyName && info?.strategyName !== strategyName) {
return false;
}
return info && info._id;
},
async getConnectingSession(req, strategyName) {
const info = await self.getConnectingInfo(req);
if (strategyName && info?.strategyName !== strategyName) {
return false;
}
return info && info.session;
},
async getConnectingInfo(req) {
const cookie = req.cookies['apos-connect'];
if (!cookie) {
return null;
}
const [ strategyName, nonce ] = cookie.split(':');
if (!(strategyName && nonce)) {
return null;
}
const safe = await self.apos.user.safe.findOne({
[`connectionRequests.${strategyName}.nonce`]: nonce
});
if (!safe) {
return null;
}
if (safe.connectionRequests[strategyName].expiresAt < Date.now()) {
return null;
}
return {
_id: safe._id,
session: safe.connectionRequests[strategyName].session,
strategyName
};
},
// Returns an array of email addresses found in the user's
// profile, via profile.emails[n].value, profile.emails[n] (a string),
// or profile.email. Passport strategies usually normalize
// to the first of the three.
getRelevantEmailsFromProfile(spec, profile) {
let emails = [];
if (Array.isArray(profile.emails) && profile.emails.length) {
(profile.emails || []).forEach(email => {
if (typeof (email) === 'string') {
// maybe someone does this as simple strings...
emails.push(email);
// but google does it as objects with value properties
} else if (email && email.value) {
emails.push(email.value);
}
});
} else if (profile.email) {
emails.push(profile.email);
}
if (spec.emailDomain) {
emails = emails.filter(email => {
const endsWith = '@' + spec.emailDomain;
return email.substr(email.length - endsWith.length) === endsWith;
});
}
return emails;
},
// Create a new user based on a profile. This occurs only
// if the "create" option is set and a user arrives who has
// a valid passport profile but does not exist in the local database.
async createUser(spec, profile) {
const user = self.apos.user.newInstance();
user.role = await self.userRole();
user.username = profile.username;
user.title = profile.displayName || profile.username || '';
user[spec.name + 'Id'] = profile.id;
if (!user.username) {
user.username = self.apos.util.slugify(user.title);
}
const emails = self.getRelevantEmailsFromProfile(spec, profile);
if (emails.length) {
user.email = emails[0];
}
if (profile.name) {
user.firstName = profile.name.givenName;
if (profile.name.middleName) {
user.firstName += ' ' + profile.name.middleName;
}
user.lastName = profile.name.familyName;
} else if (profile.firstName || profile.lastName) {
user.firstName = profile.firstName;
user.lastName = profile.lastName;
} else if (profile.displayName) {
const parsedName = humanname.parse(profile.displayName);
user.firstName = parsedName.firstName;
user.lastName = parsedName.lastName;
}
const req = self.apos.task.getReq();
if (spec.import) {
// Allow for specialized import of more fields
spec.import(profile, user);
}
await self.apos.user.insert(req, user);
return user;
},
// Overridable method for determining the default role
// of newly created users.
async userRole() {
return (self.options.create && self.options.create.role) || 'guest';
}
};
},
handlers(self) {
return {
'@apostrophecms/login:afterSessionLogin': {
async restoreConnectionSession(req) {
const session = await self.getConnectingSession(req);
if (session) {
for (const [ key, value ] of Object.entries(session)) {
req.session[key] = value;
}
}
req.res.clearCookie('apos-connect');
},
async redirectToNewLocale(req) {
if (!req.session.passportLocale) {
return;
}
const i18n = self.apos.i18n;
const {
oldLocale,
newLocale,
oldAposDocId
} = req.session.passportLocale;
delete req.session.passportLocale;
const crossDomainSessionToken = self.apos.util.generateId();
await self.apos.cache.set('@apostrophecms/i18n:cross-domain-sessions', crossDomainSessionToken, req.session, 60 * 60);
let doc = await self.apos.doc.find(req, {
aposDocId: oldAposDocId
}).locale(`${oldLocale}:draft`).relationships(false).areas(false).toObject();
if (doc && doc.aposDocId) {
doc = await self.apos.doc.find(req, {
aposDocId: doc.aposDocId
}).locale(`${newLocale}:draft`).toObject();
}
let route;
if (doc) {
const action = self.apos.page.isPage(doc)
? self.apos.page.action
: self.apos.doc.getManager(doc).action;
route = `${action}/${doc._id}/locale/${newLocale}`;
} else {
// Fall back to home page, with appropriate prefix
route = '/';
if (i18n.locales[newLocale] && i18n.locales[newLocale].prefix) {
route = i18n.locales[newLocale].prefix + '/';
}
}
let url = self.apos.url.build(route, {
aposLocale: req.oldLocale,
aposCrossDomainSessionToken: crossDomainSessionToken
});
if (i18n.locales[newLocale] && i18n.locales[newLocale].hostname) {
const oldLocale = req.locale;
// Force use of correct hostname for new locale
req.locale = newLocale;
url = self.apos.page.getBaseUrl(req) + url;
req.locale = oldLocale;
}
req.session.passportRedirect = url;
}
},
'apostrophe:modulesRegistered': {
addRoutes() {
self.options.strategies.forEach(spec => {
self.addLoginRoute(spec);
self.addCallbackRoute(spec);
self.addFailureRoute(spec);
self.addConnectRoute(spec);
});
}
}
};
},
tasks(self) {
return {
listUrls: {
usage: 'Run this task to list the login URLs for each registered strategy.\n' +
'This is helpful when writing markup to invite users to log in.',
task: () => {
// eslint-disable-next-line no-console
console.log('These are the login URLs you may wish to link users to:\n');
self.options.strategies.forEach(spec => {
// eslint-disable-next-line no-console
console.log(`${spec.label}: ${self.getLoginUrl(spec, true)}`);
});
// eslint-disable-next-line no-console
console.log('\nThese are the callback URLs you may need to configure on sites:\n');
self.options.strategies.forEach(spec => {
// eslint-disable-next-line no-console
console.log(`${spec.label}: ${self.getCallbackUrl(spec, true)}`);
});
}
}
};
},
components(self) {
return {
loginLinks(req, data) {
return {
links: self.options.strategies.map(spec => {
let href = self.getLoginUrl(spec, true);
if (Object.keys(self.apos.i18n.locales).length > 1) {
const context = req.data.piece || req.data.page;
href = self.apos.url.build(href, {
oldLocale: req.locale,
newLocale: req.locale.replace(':draft', ':published'),
oldAposDocId: (context && context.aposDocId)
});
}
return {
name: spec.name,
label: spec.label,
href
};
})
};
}
};
}
};
function getBundleModuleNames() {
const source = path.join(__dirname, './modules/@apostrophecms');
return fs
.readdirSync(source, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => `@apostrophecms/${dirent.name}`);
}