Move 2fa validation in one place

This commit is contained in:
Johannes Zellner
2020-02-06 15:36:14 +01:00
parent 12aa8ac0ad
commit 7c5a258af3
3 changed files with 21 additions and 28 deletions

View File

@@ -13,7 +13,8 @@ var accesscontrol = require('../accesscontrol.js'),
BoxError = require('../boxerror.js'),
externalLdap = require('../externalldap.js'),
HttpError = require('connect-lastmile').HttpError,
users = require('../users.js');
users = require('../users.js'),
speakeasy = require('speakeasy');
function passwordAuth(req, res, next) {
assert.strictEqual(typeof req.body, 'object');
@@ -24,7 +25,21 @@ function passwordAuth(req, res, next) {
const username = req.body.username;
const password = req.body.password;
// TODO we should only do this for dashboard logins
function check2FA(user) {
assert.strictEqual(typeof user, 'object');
if (!user.ghost && !user.appPassword && user.twoFactorAuthenticationEnabled) {
if (!req.body.totpToken) return next(new HttpError(401, 'A totpToken must be provided'));
let verified = speakeasy.totp.verify({ secret: user.twoFactorAuthenticationSecret, encoding: 'base32', token: req.body.totpToken, window: 2 });
if (!verified) return next(new HttpError(401, 'Invalid totpToken'));
}
req.user = user;
next();
}
function createAndVerifyUserIfNotExist(identifier, password) {
assert.strictEqual(typeof identifier, 'string');
assert.strictEqual(typeof password, 'string');
@@ -37,9 +52,7 @@ function passwordAuth(req, res, next) {
if (error && error.reason === BoxError.INVALID_CREDENTIALS) return next(new HttpError(401, 'Unauthorized'));
if (error) return next(new HttpError(500, error));
req.user = result;
next();
check2FA(result);
});
}
@@ -50,9 +63,7 @@ function passwordAuth(req, res, next) {
if (error) return next(new HttpError(500, error));
if (!result) return next(new HttpError(401, 'Unauthorized'));
req.user = result;
next();
check2FA(result);
});
} else {
users.verifyWithEmail(username, password, users.AP_WEBADMIN, function (error, result) {
@@ -61,9 +72,7 @@ function passwordAuth(req, res, next) {
if (error) return next(new HttpError(500, error));
if (!result) return next(new HttpError(401, 'Unauthorized'));
req.user = result;
next();
check2FA(result);
});
}
}