This repository has been archived by the owner on May 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
library.js
328 lines (254 loc) · 8.62 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
/*
* library.js
*
* Copyright © 2015-2018 Antergos
*
* This file is part of nodebb-plugin-sso-auth0.
*
* nodebb-plugin-sso-auth0 is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* nodebb-plugin-sso-auth0 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 General Public License for more details.
*
* The following additional terms are in effect as per Section 7 of the license:
*
* The preservation of all legal notices and author attributions in
* the material or in the Appropriate Legal Notices displayed
* by works containing it is required.
*
* You should have received a copy of the GNU General Public License
* along with nodebb-plugin-sso-auth0; If not, see <http://www.gnu.org/licenses/>.
*/
// curl -X PUT https://packages.nodebb.org/api/v1/plugins/nodebb-plugin-sso-auth0
const USER = require.main.require( './src/user' );
const DB = require.main.require( './src/database' );
const META = require.main.require( './src/meta' );
const NCONF = require.main.require( 'nconf' );
const PASSPORT = require.main.require( 'passport' );
const AUTH_CONTROLLER = require.main.require( './src/controllers/authentication' );
const WINSTON = require.main.require( 'winston' );
const AUTH0_STRATEGY = require( 'passport-auth0' ).Strategy;
const ADMIN_ICON = 'fa-star';
const ADMIN_ROUTE = '/plugins/sso-auth0';
const CALLBACK_URL = NCONF.get( 'url' ) + '/auth/auth0/callback';
const STRATEGY_INFO = {
name: 'auth0',
url: '/auth/auth0',
callbackURL: '/auth/auth0/callback',
icon: ADMIN_ICON,
scope: 'user email',
};
let _self = null;
class Auth0 {
constructor() {
if ( null !== _self ) {
return _self;
}
_self = bind_this( this );
this.settings = null;
return _self;
}
/**
* Wrapper for callback-based async functions.
*
* @param func
* @param args
*
* @return Array
*/
async _do_async( func, ...args ) {
return new Promise( (resolve, reject) => {
const done = (err, ...args) => resolve( [err, ...args] );
return func( ...args, done );
} );
}
_error( error, data = {} ) {
console.error( `AUTH0 ERROR - ENO-${error}: ` + JSON.stringify( data ) );
return `An error has occurred. Please report this error to us and include the
following error code in your report: ENO-${error}.`;
}
addMenuItem( custom_header, callback ) {
custom_header.authentication.push({
'route': ADMIN_ROUTE,
'icon': ADMIN_ICON,
'name': this.constructor.name,
});
return callback( null, custom_header );
}
async deleteUserData( data, callback ) {
const uid = data.uid;
const do_error = error => WINSTON.error( `[sso-auth0] Could not remove OAuthId data for uid ${uid}. Error: ${error}` );
let [err, auth0id] = await this._do_async( USER.getUserField, uid, 'auth0id' );
if ( err ) {
do_error( err );
return callback( err );
}
[err, res] = await this._do_async( DB.deleteObjectField, 'auth0id:uid', auth0id );
if ( err ) {
do_error( err );
return callback( err );
}
return callback( null, uid );
}
getEmailFromProfile( profile ) {
let email = profile.emails;
if ( Array.isArray( email ) && email.length ) {
email = email[0];
}
if ( 'object' === typeof email && 'value' in email ) {
email = email.value;
}
if ( 'object' === typeof email && 'email' in email ) {
email = email.email;
}
return email;
}
async handleAuthRequest( request, accessToken, refreshToken, profile, done ) {
if ( this.isUserLoggedIn( request ) ) {
return done( null, request.user );
}
const email = this.getEmailFromProfile( profile );
if ( 'string' !== typeof email || ! email ) {
return done( this._error( '010', {user: request.user, profile: profile} ) );
}
const [err, user] = await this.login( profile.id, profile.nickname, email, request );
if ( err ) {
return done( this._error( '014', err ) );
}
const [error] = await this.onUserLoggedIn( user.uid, request );
return done( error, error ? null : user );
}
isUserLoggedIn( request ) {
return ( 'user' in request && 'uid' in request.user && parseInt( request.user.uid ) > 0 );
}
async _getAssociation( data, callback ) {
const [err, auth0id] = await this._do_async( USER.getUserField, data.uid, 'auth0id' );
if ( err ) {
return callback( this._error( '015', {err, data} ) );
}
const association = {
associated: Boolean( auth0id ),
name: this.constructor.name,
icon: ADMIN_ICON,
url: NCONF.get('url') + '/auth/auth0',
};
data.associations.push( association );
return callback( null, data );
}
getAssociation( data, callback ) {
try {
return this._getAssociation( data, callback );
} catch(err) {
return this._error( '012', err );
}
}
async _getStrategy( strategies, callback ) {
let err;
[err, this.settings] = await this._do_async( META.settings.get, 'sso-auth0' );
if ( err ) {
return callback( this._error( '011a', err ), strategies );
}
if ( ! ['id', 'secret', 'domain'].every( key => key && key in this.settings ) ) {
let msg = '[Auth0 SSO]: Before you can use this plugin, you must configure it. ';
msg += 'You can access the settings in the Social Authentication menu.';
console.info( msg );
return callback( null, strategies );
}
const options = {
domain: this.settings.domain,
clientID: this.settings.id,
clientSecret: this.settings.secret,
callbackURL: NCONF.get('url') + '/auth/auth0/callback',
passReqToCallback: true,
scope: STRATEGY_INFO.scope,
};
PASSPORT.use( new AUTH0_STRATEGY( options, (...args) => this.handleAuthRequest(...args) ) );
strategies.push( STRATEGY_INFO );
return callback( null, strategies );
}
getStrategy( data, callback ) {
try {
return this._getStrategy( data, callback );
} catch(err) {
return this._error( '013', err );
}
}
async getUidByAuth0Id( auth0id ) {
return this._do_async( DB.getObjectField, 'auth0id:uid', auth0id );
}
init( data, callback ) {
const renderAdmin = ( req, resp ) => resp.render( 'admin/plugins/sso-auth0', {callbackURL: CALLBACK_URL} );
const logoutCallback = ( req, resp ) => resp.render( '/', {logoutFlag: true} );
data.router.get( '/admin/plugins/sso-auth0', data.middleware.admin.buildHeader, renderAdmin );
data.router.get( '/api/admin/plugins/sso-auth0', renderAdmin );
data.router.get( '/auth/auth0/logout/callback', logoutCallback );
return callback( null, data );
}
async login( auth0id, username, email, request ) {
let [err, uid] = await this.getUidByAuth0Id( auth0id );
if ( err ) {
return [err, {}];
}
if ( uid ) {
// Existing User
return [null, {uid: uid}];
}
[err, uid] = await this._do_async( USER.getUidByEmail, email );
if ( err ) {
return [err, {}];
}
if ( ! uid ) {
// New account -- create
[err, uid] = await this._do_async( USER.create, {username: username, email: email} );
if ( err ) {
return [err, {}];
}
}
// Save Auth0-specific information to the user profile
USER.setUserField( uid, 'auth0id', auth0id );
DB.setObjectField( 'auth0id:uid', auth0id, uid );
return [null, {uid: uid}];
}
noLoginAfterRegister( params, callback ) {
params.res.locals.processLogin = false;
setTimeout( () => callback( null, params ), 1000 );
}
async onUserLoggedIn( uid, request ) {
// NodeBB onSuccessfulLogin hook
return this._do_async( AUTH_CONTROLLER.onSuccessfulLogin, request, uid );
}
whitelistUserFields( data, callback ) {
data.whitelist.push( 'auth0id' );
return setImmediate( callback, null, data );
}
}
/**
* Binds `this` to class instance, `context`, for all of the instance's methods.
*
* @example At the beginning of the instance's constructor method: `let _self = bind_this( this );`.
* Then, at the end of the instance's constructor method: `return _self;`.
*
* @param {object} context An ES6 class instance with at least one method.
*
* @return {object} `context` with `this` bound to it for all of its methods.
*/
function bind_this( context ) {
for ( let obj = context; obj; obj = Object.getPrototypeOf( obj ) ) {
// Handle only our methods
if ( 'Object' === obj.constructor.name ) {
break;
}
for ( const method of Object.getOwnPropertyNames( obj ) ) {
if ( 'function' === typeof context[method] && 'constructor' !== method ) {
context[method] = context[method].bind( context );
}
}
}
return context;
}
module.exports = new Auth0();