2023-04-06 12:59:25 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
2023-06-14 13:15:00 +00:00
|
|
|
Self.remoteMethod('validateAuth', {
|
2023-04-06 12:59:25 +00:00
|
|
|
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'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-06-14 13:15:00 +00:00
|
|
|
Self.validateAuth = async function(username, password, code) {
|
|
|
|
await Self.validateCode(code);
|
|
|
|
return Self.validateLogin(username, password);
|
|
|
|
};
|
|
|
|
|
|
|
|
Self.validateCode = async(username, code) => {
|
|
|
|
const {AuthCode} = Self.app.models;
|
2023-04-06 12:59:25 +00:00
|
|
|
|
|
|
|
const authCode = await AuthCode.findOne({
|
|
|
|
where: {
|
|
|
|
code: code
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2023-04-13 09:54:56 +00:00
|
|
|
const expired = authCode && Date.vnNow() > authCode.expires;
|
2023-04-06 12:59:25 +00:00
|
|
|
if (!authCode || expired)
|
|
|
|
throw new UserError('Invalid or expired verification code');
|
|
|
|
|
|
|
|
const user = await Self.findById(authCode.userFk, {
|
|
|
|
fields: ['name', 'twoFactor']
|
|
|
|
});
|
2023-06-14 13:15:00 +00:00
|
|
|
console.log(username, code);
|
2023-04-06 12:59:25 +00:00
|
|
|
if (user.name !== username)
|
|
|
|
throw new UserError('Authentication failed');
|
|
|
|
|
|
|
|
await authCode.destroy();
|
|
|
|
};
|
|
|
|
};
|