74 lines
2.1 KiB
JavaScript
74 lines
2.1 KiB
JavaScript
|
const UserError = require('vn-loopback/util/user-error');
|
||
|
|
||
|
module.exports = Self => {
|
||
|
Self.remoteMethodCtx('validateAuth', {
|
||
|
description: 'Login a user with username/email and password',
|
||
|
accepts: [
|
||
|
{
|
||
|
arg: 'user',
|
||
|
type: 'String',
|
||
|
description: 'The user name or email',
|
||
|
required: true
|
||
|
},
|
||
|
{
|
||
|
arg: 'password',
|
||
|
type: 'String',
|
||
|
description: 'The password'
|
||
|
},
|
||
|
{
|
||
|
arg: 'code',
|
||
|
type: 'String',
|
||
|
description: 'The auth code'
|
||
|
}
|
||
|
],
|
||
|
returns: {
|
||
|
type: 'object',
|
||
|
root: true
|
||
|
},
|
||
|
http: {
|
||
|
path: `/validate-auth`,
|
||
|
verb: 'POST'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.validateAuth = async function(ctx, username, password, code) {
|
||
|
const {AuthCode, UserAccess} = Self.app.models;
|
||
|
|
||
|
const authCode = await AuthCode.findOne({
|
||
|
where: {
|
||
|
code: code
|
||
|
}
|
||
|
});
|
||
|
|
||
|
const expired = Date.now() > authCode.expires;
|
||
|
if (!authCode || expired)
|
||
|
throw new UserError('Invalid or expired verification code');
|
||
|
|
||
|
const user = await Self.findById(authCode.userFk, {
|
||
|
fields: ['name', 'twoFactor']
|
||
|
});
|
||
|
|
||
|
if (user.name !== username)
|
||
|
throw new UserError('Authentication failed');
|
||
|
|
||
|
const headers = ctx.req.headers;
|
||
|
let platform = headers['sec-ch-ua-platform'];
|
||
|
let browser = headers['sec-ch-ua'];
|
||
|
|
||
|
if (platform) platform = platform.replace(/['"]+/g, '');
|
||
|
if (browser) browser = browser.split(';')[0].replace(/['"]+/g, '');
|
||
|
|
||
|
await UserAccess.upsertWithWhere({userFk: authCode.userFk}, {
|
||
|
userFk: authCode.userFk,
|
||
|
ip: ctx.req.connection.remoteAddress,
|
||
|
agent: headers['user-agent'],
|
||
|
platform: platform,
|
||
|
browser: browser
|
||
|
});
|
||
|
|
||
|
await authCode.destroy();
|
||
|
|
||
|
return Self.login(ctx, username, password);
|
||
|
};
|
||
|
};
|