2015-07-20 00:09:47 -07:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
|
|
exports = module.exports = {
|
2017-11-02 10:31:11 -07:00
|
|
|
login: login
|
2015-07-20 00:09:47 -07:00
|
|
|
};
|
|
|
|
|
|
2018-05-01 13:40:25 -07:00
|
|
|
var clients = require('../clients.js'),
|
2015-07-20 00:09:47 -07:00
|
|
|
passport = require('passport'),
|
|
|
|
|
HttpError = require('connect-lastmile').HttpError,
|
2018-04-26 20:10:46 +02:00
|
|
|
HttpSuccess = require('connect-lastmile').HttpSuccess,
|
|
|
|
|
speakeasy = require('speakeasy');
|
2015-07-20 00:09:47 -07:00
|
|
|
|
|
|
|
|
function login(req, res, next) {
|
|
|
|
|
passport.authenticate('local', function (error, user) {
|
|
|
|
|
if (error) return next(new HttpError(500, error));
|
|
|
|
|
if (!user) return next(new HttpError(401, 'Invalid credentials'));
|
|
|
|
|
|
2018-03-02 19:26:55 +01:00
|
|
|
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || null;
|
|
|
|
|
|
2018-05-14 14:49:31 -07:00
|
|
|
if (!user.ghost && user.twoFactorAuthenticationEnabled) {
|
2018-04-26 20:10:46 +02:00
|
|
|
if (!req.body.totpToken) return next(new HttpError(401, 'A totpToken must be provided'));
|
|
|
|
|
|
2019-07-23 14:42:03 -07:00
|
|
|
let verified = speakeasy.totp.verify({ secret: user.twoFactorAuthenticationSecret, encoding: 'base32', token: req.body.totpToken, window: 2 });
|
2018-04-26 20:10:46 +02:00
|
|
|
if (!verified) return next(new HttpError(401, 'Invalid totpToken'));
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-27 14:50:41 -07:00
|
|
|
const auditSource = { authType: 'cli', ip: ip };
|
|
|
|
|
clients.issueDeveloperToken(user, auditSource, function (error, result) {
|
2015-07-20 00:09:47 -07:00
|
|
|
if (error) return next(new HttpError(500, error));
|
|
|
|
|
|
2018-05-01 13:40:25 -07:00
|
|
|
next(new HttpSuccess(200, result));
|
2015-07-20 00:09:47 -07:00
|
|
|
});
|
2018-05-01 13:58:13 -07:00
|
|
|
})(req, res, next);
|
2015-07-20 00:09:47 -07:00
|
|
|
}
|
2015-07-27 13:08:07 +02:00
|
|
|
|