forked from NodeBB/NodeBB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authentication.js
392 lines (339 loc) · 10.5 KB
/
authentication.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
"use strict";
var async = require('async');
var winston = require('winston');
var passport = require('passport');
var nconf = require('nconf');
var validator = require('validator');
var _ = require('underscore');
var db = require('../database');
var meta = require('../meta');
var user = require('../user');
var plugins = require('../plugins');
var utils = require('../../public/src/utils');
var Password = require('../password');
var authenticationController = {};
authenticationController.register = function(req, res, next) {
var registrationType = meta.config.registrationType || 'normal';
if (registrationType === 'disabled') {
return res.sendStatus(403);
}
var userData = {};
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
userData[key] = req.body[key];
}
}
async.waterfall([
function(next) {
if (registrationType === 'invite-only' || registrationType === 'admin-invite-only') {
user.verifyInvitation(userData, next);
} else {
next();
}
},
function(next) {
if (!userData.email) {
return next(new Error('[[error:invalid-email]]'));
}
if (!userData.username || userData.username.length < meta.config.minimumUsernameLength) {
return next(new Error('[[error:username-too-short]]'));
}
if (userData.username.length > meta.config.maximumUsernameLength) {
return next(new Error('[[error:username-too-long'));
}
user.isPasswordValid(userData.password, next);
},
function(next) {
res.locals.processLogin = true; // set it to false in plugin if you wish to just register only
plugins.fireHook('filter:register.check', {req: req, res: res, userData: userData}, next);
},
function(data, next) {
if (registrationType === 'normal' || registrationType === 'invite-only' || registrationType === 'admin-invite-only') {
registerAndLoginUser(req, res, userData, next);
} else if (registrationType === 'admin-approval') {
addToApprovalQueue(req, userData, next);
}
}
], function(err, data) {
if (err) {
return res.status(400).send(err.message);
}
if (req.body.userLang) {
user.setSetting(data.uid, 'userLang', req.body.userLang);
}
res.json(data);
});
};
function registerAndLoginUser(req, res, userData, callback) {
var uid;
async.waterfall([
function(next) {
plugins.fireHook('filter:register.interstitial', {
userData: userData,
interstitials: []
}, function(err, data) {
// If interstitials are found, save registration attempt into session and abort
var deferRegistration = data.interstitials.length;
if (!deferRegistration) {
return next();
} else {
userData.register = true;
req.session.registration = userData;
return res.json({ referrer: nconf.get('relative_path') + '/register/complete' });
}
});
},
function(next) {
user.create(userData, next);
},
function(_uid, next) {
uid = _uid;
if (res.locals.processLogin) {
authenticationController.doLogin(req, uid, next);
} else {
next();
}
},
function(next) {
user.deleteInvitationKey(userData.email);
plugins.fireHook('filter:register.complete', {uid: uid, referrer: req.body.referrer || nconf.get('relative_path') + '/'}, next);
}
], callback);
}
function addToApprovalQueue(req, userData, callback) {
async.waterfall([
function(next) {
userData.ip = req.ip;
user.addToApprovalQueue(userData, next);
},
function(next) {
next(null, {message: '[[register:registration-added-to-queue]]'});
}
], callback);
}
authenticationController.registerComplete = function(req, res, next) {
// For the interstitials that respond, execute the callback with the form body
plugins.fireHook('filter:register.interstitial', {
userData: req.session.registration,
interstitials: []
}, function(err, data) {
var callbacks = data.interstitials.reduce(function(memo, cur) {
if (cur.hasOwnProperty('callback') && typeof cur.callback === 'function') {
memo.push(async.apply(cur.callback, req.session.registration, req.body));
}
return memo;
}, []);
var done = function() {
delete req.session.registration;
if (req.session.returnTo) {
res.redirect(req.session.returnTo);
} else {
res.redirect(nconf.get('relative_path') + '/');
}
}
async.parallel(callbacks, function(err) {
if (err) {
req.flash('error', err.message);
return res.redirect(nconf.get('relative_path') + '/register/complete');
}
if (req.session.registration.register === true) {
res.locals.processLogin = true;
registerAndLoginUser(req, res, req.session.registration, done);
} else {
// Clear registration data in session
done();
}
});
});
};
authenticationController.registerAbort = function(req, res, next) {
// End the session and redirect to home
req.session.destroy(function() {
res.redirect(nconf.get('relative_path') + '/');
});
};
authenticationController.login = function(req, res, next) {
// Handle returnTo data
if (req.body.hasOwnProperty('returnTo') && !req.session.returnTo) {
req.session.returnTo = req.body.returnTo;
}
if (plugins.hasListeners('action:auth.overrideLogin')) {
return continueLogin(req, res, next);
}
var loginWith = meta.config.allowLoginWith || 'username-email';
if (req.body.username && utils.isEmailValid(req.body.username) && loginWith.indexOf('email') !== -1) {
user.getUsernameByEmail(req.body.username, function(err, username) {
if (err) {
return next(err);
}
req.body.username = username ? username : req.body.username;
continueLogin(req, res, next);
});
} else if (loginWith.indexOf('username') !== -1 && !validator.isEmail(req.body.username)) {
continueLogin(req, res, next);
} else {
res.status(500).send('[[error:wrong-login-type-' + loginWith + ']]');
}
};
function continueLogin(req, res, next) {
passport.authenticate('local', function(err, userData, info) {
if (err) {
return res.status(403).send(err.message);
}
if (!userData) {
if (typeof info === 'object') {
info = '[[error:invalid-username-or-password]]';
}
return res.status(403).send(info);
}
var passwordExpiry = userData.passwordExpiry !== undefined ? parseInt(userData.passwordExpiry, 10) : null;
// Alter user cookie depending on passed-in option
if (req.body.remember === 'on') {
var duration = 1000 * 60 * 60 * 24 * (parseInt(meta.config.loginDays, 10) || 14);
req.session.cookie.maxAge = duration;
req.session.cookie.expires = new Date(Date.now() + duration);
} else {
req.session.cookie.maxAge = false;
req.session.cookie.expires = false;
}
if (passwordExpiry && passwordExpiry < Date.now()) {
winston.verbose('[auth] Triggering password reset for uid ' + userData.uid + ' due to password policy');
req.session.passwordExpired = true;
user.reset.generate(userData.uid, function(err, code) {
res.status(200).send(nconf.get('relative_path') + '/reset/' + code);
});
} else {
authenticationController.doLogin(req, userData.uid, function(err) {
if (err) {
return res.status(403).send(err.message);
}
if (!req.session.returnTo) {
res.status(200).send(nconf.get('relative_path') + '/');
} else {
var next = req.session.returnTo;
delete req.session.returnTo;
res.status(200).send(next);
}
});
}
})(req, res, next);
}
authenticationController.doLogin = function(req, uid, callback) {
if (!uid) {
return callback();
}
req.login({uid: uid}, function(err) {
if (err) {
return callback(err);
}
authenticationController.onSuccessfulLogin(req, uid, callback);
});
};
authenticationController.onSuccessfulLogin = function(req, uid, callback) {
callback = callback || function() {};
var uuid = utils.generateUUID();
req.session.meta = {};
delete req.session.forceLogin;
// Associate IP used during login with user account
user.logIP(uid, req.ip);
req.session.meta.ip = req.ip;
// Associate metadata retrieved via user-agent
req.session.meta = _.extend(req.session.meta, {
uuid: uuid,
datetime: Date.now(),
platform: req.useragent.platform,
browser: req.useragent.browser,
version: req.useragent.version
});
// Associate login session with user
async.parallel([
function (next) {
user.auth.addSession(uid, req.sessionID, next);
},
function (next) {
db.setObjectField('uid:' + uid + 'sessionUUID:sessionId', uuid, req.sessionID, next);
}
], function(err) {
if (err) {
return callback(err);
}
plugins.fireHook('action:user.loggedIn', uid);
callback();
});
};
authenticationController.localLogin = function(req, username, password, next) {
if (!username) {
return next(new Error('[[error:invalid-username]]'));
}
var userslug = utils.slugify(username);
var uid, userData = {};
async.waterfall([
function (next) {
user.isPasswordValid(password, next);
},
function (next) {
user.getUidByUserslug(userslug, next);
},
function (_uid, next) {
if (!_uid) {
return next(new Error('[[error:no-user]]'));
}
uid = _uid;
user.auth.logAttempt(uid, req.ip, next);
},
function (next) {
async.parallel({
userData: function(next) {
db.getObjectFields('user:' + uid, ['password', 'passwordExpiry'], next);
},
isAdmin: function(next) {
user.isAdministrator(uid, next);
},
banned: function(next) {
user.isBanned(uid, next);
}
}, next);
},
function (result, next) {
userData = result.userData;
userData.uid = uid;
userData.isAdmin = result.isAdmin;
if (!result.isAdmin && parseInt(meta.config.allowLocalLogin, 10) === 0) {
return next(new Error('[[error:local-login-disabled]]'));
}
if (!userData || !userData.password) {
return next(new Error('[[error:invalid-user-data]]'));
}
if (result.banned) {
return next(new Error('[[error:user-banned]]'));
}
Password.compare(password, userData.password, next);
},
function (passwordMatch, next) {
if (!passwordMatch) {
return next(new Error('[[error:invalid-password]]'));
}
user.auth.clearLoginAttempts(uid);
next(null, userData, '[[success:authentication-successful]]');
}
], next);
};
authenticationController.logout = function(req, res, next) {
if (req.user && parseInt(req.user.uid, 10) > 0 && req.sessionID) {
var uid = parseInt(req.user.uid, 10);
user.auth.revokeSession(req.sessionID, uid, function(err) {
if (err) {
return next(err);
}
req.logout();
req.session.destroy();
user.setUserField(uid, 'lastonline', Date.now() - 300000);
plugins.fireHook('static:user.loggedOut', {req: req, res: res, uid: uid}, function() {
res.status(200).send('');
});
});
} else {
res.status(200).send('');
}
};
module.exports = authenticationController;