-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
601 lines (519 loc) · 17.5 KB
/
library.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
'use strict';
(function (module) {
/*
Welcome to the SSO OAuth plugin! If you're inspecting this code, you're probably looking to
hook up NodeBB with your existing OAuth endpoint.
Step 1: Fill in the "constants" section below with the requisite informaton. Either the "oauth"
or "oauth2" section needs to be filled, depending on what you set "type" to.
Step 2: Give it a whirl. If you see the congrats message, you're doing well so far!
Step 3: Customise the `parseUserReturn` method to normalise your user route's data return into
a format accepted by NodeBB. Instructions are provided there. (Line 146)
Step 4: If all goes well, you'll be able to login/register via your OAuth endpoint credentials.
*/
const User = require.main.require('./src/user');
const Groups = require.main.require('./src/groups');
const db = require.main.require('./src/database');
const authenticationController = require.main.require('./src/controllers/authentication');
const async = require('async');
const passport = module.parent.require('passport');
const nconf = module.parent.require('nconf');
const winston = module.parent.require('winston');
/**
* REMEMBER
* Never save your OAuth Key/Secret or OAuth2 ID/Secret pair in code! It could be published and leaked accidentally.
* Save it into your config.json file instead:
*
* {
* ...
* "oauth": {
* "id": "someoauthid",
* "secret": "youroauthsecret"
* }
* ...
* }
*
* ... or use environment variables instead:
*
* `OAUTH__ID=someoauthid OAUTH__SECRET=youroauthsecret node app.js`
*/
const constants = Object.freeze({
type: 'oauth2', // Either 'oauth' or 'oauth2'
name: 'XDA', // Something unique to your OAuth provider in lowercase, like "github", or "nodebb"
oauth: {
requestTokenURL: '',
accessTokenURL: '',
userAuthorizationURL: '',
consumerKey: nconf.get('oauth:key'), // don't change this line
consumerSecret: nconf.get('oauth:secret'), // don't change this line
},
oauth2: {
authorizationURL: 'https://api.xda-developers.com/oauth2/authorize',
tokenURL: 'https://api.xda-developers.com/oauth2/grant',
clientID: nconf.get('oauth:id'), // don't change this line
clientSecret: nconf.get('oauth:secret'), // don't change this line
},
userRoute: 'https://api.xda-developers.com/v3/user', // This is the address to your app's "user profile" API endpoint (expects JSON)
});
const OAuth = {};
let configOk = false;
let passportOAuth;
let opts;
if (!constants.name) {
winston.error('[sso-oauth] Please specify a name for your OAuth provider (library.js:32)');
} else if (!constants.type || (constants.type !== 'oauth' && constants.type !== 'oauth2')) {
winston.error('[sso-oauth] Please specify an OAuth strategy to utilise (library.js:31)');
} else if (!constants.userRoute) {
winston.error('[sso-oauth] User Route required (library.js:31)');
} else {
configOk = true;
}
OAuth.getStrategy = function (strategies, callback) {
if (configOk) {
passportOAuth = require('passport-oauth')[constants.type === 'oauth' ? 'OAuthStrategy' : 'OAuth2Strategy'];
if (constants.type === 'oauth') {
// OAuth options
opts = constants.oauth;
opts.callbackURL = nconf.get('url') + '/auth/' + constants.name + '/callback';
passportOAuth.Strategy.prototype.userProfile = function (token, secret, params, done) {
this._oauth.get(constants.userRoute, token, secret, function (err, body/* , res */) {
if (err) {
return done(err);
}
try {
var json = JSON.parse(body);
OAuth.parseUserReturn(json, function (err, profile) {
if (err) return done(err);
profile.provider = constants.name;
done(null, profile);
});
} catch (e) {
done(e);
}
});
};
} else if (constants.type === 'oauth2') {
// OAuth 2 options
opts = constants.oauth2;
opts.callbackURL = nconf.get('url') + '/auth/' + constants.name + '/callback';
passportOAuth.Strategy.prototype.userProfile = function (accessToken, done) {
//console.log('Trying ' + constants.userRoute + ' with ' + accessToken);
// this._oauth2.setAuthMethod('Bearer'); // Default
this._oauth2.useAuthorizationHeaderforGET(true);
this._oauth2.get(constants.userRoute, accessToken, function (err, body, res) {
//console.log('Debug: ', err, body, res);
if (err) {
console.log(err);
return done(err);
}
try {
var json = JSON.parse(body);
OAuth.parseUserReturn(json, function (err, profile) {
if (err) return done(err);
profile.provider = constants.name;
done(null, profile);
});
} catch (e) {
done(e);
}
});
};
}
opts.passReqToCallback = true;
passport.use(constants.name, new passportOAuth(opts, function (req, token, secret, profile, done) {
OAuth.login({
oAuthid: profile.id,
handle: profile.displayName,
email: profile.emails[0].value,
isAdmin: profile.isAdmin,
}, function (err, user) {
if (err) {
return done(err);
}
authenticationController.onSuccessfulLogin(req, user.uid);
done(null, user);
});
}));
strategies.push({
name: constants.name,
url: '/auth/' + constants.name,
callbackURL: '/auth/' + constants.name + '/callback',
icon: 'fa-check-square',
scope: (constants.scope || '').split(','),
});
callback(null, strategies);
} else {
callback(new Error('OAuth Configuration is invalid'));
}
};
OAuth.parseUserReturn = function (data, callback) {
// Alter this section to include whatever data is necessary
// NodeBB *requires* the following: id, displayName, emails.
// Everything else is optional.
// Find out what is available by uncommenting this line:
//console.log(data);
var profile = {};
profile.id = data.userid;
profile.displayName = data.username;
profile.emails = [{ value: data.email }];
// Do you want to automatically make somebody an admin? This line might help you do that...
// profile.isAdmin = data.isAdmin ? true : false;
// Delete or comment out the next TWO (2) lines when you are ready to proceed
// process.stdout.write('===\nAt this point, you\'ll need to customise the above section to id, displayName, and emails into the "profile" object.\n===');
// return callback(new Error('Congrats! So far so good -- please see server log for details'));
// eslint-disable-next-line
callback(null, profile);
};
OAuth.login = function (payload, callback) {
OAuth.getUidByOAuthid(payload.oAuthid, function (err, uid) {
if (err) {
return callback(err);
}
if (uid !== null) {
// Existing User
callback(null, {
uid: uid,
});
} else {
// New User
var success = function (uid) {
// Save provider-specific information to the user
User.setUserField(uid, constants.name + 'Id', payload.oAuthid);
db.setObjectField(constants.name + 'Id:uid', payload.oAuthid, uid);
if (payload.isAdmin) {
Groups.join('administrators', uid, function (err) {
callback(err, {
uid: uid,
});
});
} else {
callback(null, {
uid: uid,
});
}
};
User.getUidByEmail(payload.email, function (err, uid) {
if (err) {
return callback(err);
}
if (!uid) {
User.create({
username: payload.handle,
email: payload.email,
}, function (err, uid) {
if (err) {
return callback(err);
}
success(uid);
});
} else {
success(uid); // Existing account -- merge
}
});
}
});
};
OAuth.getUidByOAuthid = function (oAuthid, callback) {
db.getObjectField(constants.name + 'Id:uid', oAuthid, function (err, uid) {
if (err) {
return callback(err);
}
callback(null, uid);
});
};
OAuth.deleteUserData = function (data, callback) {
async.waterfall([
async.apply(User.getUserField, data.uid, constants.name + 'Id'),
function (oAuthIdToDelete, next) {
db.deleteObjectField(constants.name + 'Id:uid', oAuthIdToDelete, next);
},
], function (err) {
if (err) {
winston.error('[sso-oauth] Could not remove OAuthId data for uid ' + data.uid + '. Error: ' + err);
return callback(err);
}
callback(null, data);
});
};
// If this filter is not there, the deleteUserData function will fail when getting the oauthId for deletion.
OAuth.whitelistFields = function (params, callback) {
params.whitelist.push(constants.name + 'Id');
callback(null, params);
};
module.exports = OAuth;
}(module));
Footer
© 2022 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Docs
Contact GitHub
Pricing
API
Training
Blog
About
Skip to content
This repository has been archived by the owner. It is now read-only.
xda
/
nodebb-plugin-sso-xda
Public archive
forked from julianlam/nodebb-plugin-sso-oauth
Code
Issues
Pull requests
Actions
Projects
Security
Insights
nodebb-plugin-sso-xda/library.js
@ddrager
ddrager Imports profile info
4 contributors
288 lines (243 sloc) 8.5 KB
'use strict';
(function (module) {
/*
Welcome to the SSO OAuth plugin! If you're inspecting this code, you're probably looking to
hook up NodeBB with your existing OAuth endpoint.
Step 1: Fill in the "constants" section below with the requisite informaton. Either the "oauth"
or "oauth2" section needs to be filled, depending on what you set "type" to.
Step 2: Give it a whirl. If you see the congrats message, you're doing well so far!
Step 3: Customise the `parseUserReturn` method to normalise your user route's data return into
a format accepted by NodeBB. Instructions are provided there. (Line 146)
Step 4: If all goes well, you'll be able to login/register via your OAuth endpoint credentials.
*/
const User = require.main.require('./src/user');
const Groups = require.main.require('./src/groups');
const db = require.main.require('./src/database');
const authenticationController = require.main.require('./src/controllers/authentication');
const async = require('async');
const passport = module.parent.require('passport');
const nconf = module.parent.require('nconf');
const winston = module.parent.require('winston');
/**
* REMEMBER
* Never save your OAuth Key/Secret or OAuth2 ID/Secret pair in code! It could be published and leaked accidentally.
* Save it into your config.json file instead:
*
* {
* ...
* "oauth": {
* "id": "someoauthid",
* "secret": "youroauthsecret"
* }
* ...
* }
*
* ... or use environment variables instead:
*
* `OAUTH__ID=someoauthid OAUTH__SECRET=youroauthsecret node app.js`
*/
const constants = Object.freeze({
type: 'oauth2', // Either 'oauth' or 'oauth2'
name: 'XDA', // Something unique to your OAuth provider in lowercase, like "github", or "nodebb"
oauth: {
requestTokenURL: '',
accessTokenURL: '',
userAuthorizationURL: '',
consumerKey: nconf.get('oauth:key'), // don't change this line
consumerSecret: nconf.get('oauth:secret'), // don't change this line
},
oauth2: {
authorizationURL: 'https://api.xda-developers.com/oauth2/authorize',
tokenURL: 'https://api.xda-developers.com/oauth2/grant',
clientID: nconf.get('oauth:id'), // don't change this line
clientSecret: nconf.get('oauth:secret'), // don't change this line
},
userRoute: 'https://api.xda-developers.com/v3/user', // This is the address to your app's "user profile" API endpoint (expects JSON)
});
const OAuth = {};
let configOk = false;
let passportOAuth;
let opts;
if (!constants.name) {
winston.error('[sso-oauth] Please specify a name for your OAuth provider (library.js:32)');
} else if (!constants.type || (constants.type !== 'oauth' && constants.type !== 'oauth2')) {
winston.error('[sso-oauth] Please specify an OAuth strategy to utilise (library.js:31)');
} else if (!constants.userRoute) {
winston.error('[sso-oauth] User Route required (library.js:31)');
} else {
configOk = true;
}
OAuth.getStrategy = function (strategies, callback) {
if (configOk) {
passportOAuth = require('passport-oauth')[constants.type === 'oauth' ? 'OAuthStrategy' : 'OAuth2Strategy'];
if (constants.type === 'oauth') {
// OAuth options
opts = constants.oauth;
opts.callbackURL = nconf.get('url') + '/auth/' + constants.name + '/callback';
passportOAuth.Strategy.prototype.userProfile = function (token, secret, params, done) {
this._oauth.get(constants.userRoute, token, secret, function (err, body/* , res */) {
if (err) {
return done(err);
}
try {
var json = JSON.parse(body);
OAuth.parseUserReturn(json, function (err, profile) {
if (err) return done(err);
profile.provider = constants.name;
done(null, profile);
});
} catch (e) {
done(e);
}
});
};
} else if (constants.type === 'oauth2') {
// OAuth 2 options
opts = constants.oauth2;
opts.callbackURL = nconf.get('url') + '/auth/' + constants.name + '/callback';
passportOAuth.Strategy.prototype.userProfile = function (accessToken, done) {
//console.log('Trying ' + constants.userRoute + ' with ' + accessToken);
// this._oauth2.setAuthMethod('Bearer'); // Default
this._oauth2.useAuthorizationHeaderforGET(true);
this._oauth2.get(constants.userRoute, accessToken, function (err, body, res) {
//console.log('Debug: ', err, body, res);
if (err) {
console.log(err);
return done(err);
}
try {
var json = JSON.parse(body);
OAuth.parseUserReturn(json, function (err, profile) {
if (err) return done(err);
profile.provider = constants.name;
done(null, profile);
});
} catch (e) {
done(e);
}
});
};
}
opts.passReqToCallback = true;
passport.use(constants.name, new passportOAuth(opts, function (req, token, secret, profile, done) {
OAuth.login({
oAuthid: profile.id,
handle: profile.displayName,
email: profile.emails[0].value,
isAdmin: profile.isAdmin,
}, function (err, user) {
if (err) {
return done(err);
}
authenticationController.onSuccessfulLogin(req, user.uid);
done(null, user);
});
}));
strategies.push({
name: constants.name,
url: '/auth/' + constants.name,
callbackURL: '/auth/' + constants.name + '/callback',
icon: 'fa-check-square',
scope: (constants.scope || '').split(','),
});
callback(null, strategies);
} else {
callback(new Error('OAuth Configuration is invalid'));
}
};
OAuth.parseUserReturn = function (data, callback) {
// Alter this section to include whatever data is necessary
// NodeBB *requires* the following: id, displayName, emails.
// Everything else is optional.
// Find out what is available by uncommenting this line:
//console.log(data);
var profile = {};
profile.id = data.userid;
profile.displayName = data.username;
profile.emails = [{ value: data.email }];
// Do you want to automatically make somebody an admin? This line might help you do that...
// profile.isAdmin = data.isAdmin ? true : false;
// Delete or comment out the next TWO (2) lines when you are ready to proceed
// process.stdout.write('===\nAt this point, you\'ll need to customise the above section to id, displayName, and emails into the "profile" object.\n===');
// return callback(new Error('Congrats! So far so good -- please see server log for details'));
// eslint-disable-next-line
callback(null, profile);
};
OAuth.login = function (payload, callback) {
OAuth.getUidByOAuthid(payload.oAuthid, function (err, uid) {
if (err) {
return callback(err);
}
if (uid !== null) {
// Existing User
callback(null, {
uid: uid,
});
} else {
// New User
var success = function (uid) {
// Save provider-specific information to the user
User.setUserField(uid, constants.name + 'Id', payload.oAuthid);
db.setObjectField(constants.name + 'Id:uid', payload.oAuthid, uid);
if (payload.isAdmin) {
Groups.join('administrators', uid, function (err) {
callback(err, {
uid: uid,
});
});
} else {
callback(null, {
uid: uid,
});
}
};
User.getUidByEmail(payload.email, function (err, uid) {
if (err) {
return callback(err);
}
if (!uid) {
User.create({
username: payload.handle,
email: payload.email,
}, function (err, uid) {
if (err) {
return callback(err);
}
success(uid);
});
} else {
success(uid); // Existing account -- merge
}
});
}
});
};
OAuth.getUidByOAuthid = function (oAuthid, callback) {
db.getObjectField(constants.name + 'Id:uid', oAuthid, function (err, uid) {
if (err) {
return callback(err);
}
callback(null, uid);
});
};
OAuth.deleteUserData = function (data, callback) {
async.waterfall([
async.apply(User.getUserField, data.uid, constants.name + 'Id'),
function (oAuthIdToDelete, next) {
db.deleteObjectField(constants.name + 'Id:uid', oAuthIdToDelete, next);
},
], function (err) {
if (err) {
winston.error('[sso-oauth] Could not remove OAuthId data for uid ' + data.uid + '. Error: ' + err);
return callback(err);
}
callback(null, data);
});
};
// If this filter is not there, the deleteUserData function will fail when getting the oauthId for deletion.
OAuth.whitelistFields = function (params, callback) {
params.whitelist.push(constants.name + 'Id');
callback(null, params);
};
module.exports = OAuth;
}(module));