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-21 12:17:25 +00:00
|
|
|
Self.validateAuth = async(username, password, code, options) => {
|
2023-07-03 11:33:48 +00:00
|
|
|
const myOptions = {};
|
|
|
|
if (typeof options == 'object')
|
|
|
|
Object.assign(myOptions, options);
|
2023-06-21 12:17:25 +00:00
|
|
|
|
2023-07-03 11:33:48 +00:00
|
|
|
const token = Self.validateLogin(username, password);
|
2023-06-21 12:17:25 +00:00
|
|
|
await Self.validateCode(username, code, myOptions);
|
2023-07-03 11:33:48 +00:00
|
|
|
return token;
|
2023-06-14 13:15:00 +00:00
|
|
|
};
|
|
|
|
|
2023-06-21 12:17:25 +00:00
|
|
|
Self.validateCode = async(username, code, myOptions) => {
|
2023-06-14 13:15:00 +00:00
|
|
|
const {AuthCode} = Self.app.models;
|
2023-04-06 12:59:25 +00:00
|
|
|
|
|
|
|
const authCode = await AuthCode.findOne({
|
|
|
|
where: {
|
|
|
|
code: code
|
|
|
|
}
|
2023-06-21 12:17:25 +00:00
|
|
|
}, myOptions);
|
2023-04-06 12:59:25 +00:00
|
|
|
|
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-21 12:17:25 +00:00
|
|
|
}, myOptions);
|
2023-06-19 13:06:06 +00:00
|
|
|
|
2024-08-08 09:51:46 +00:00
|
|
|
if (user.name.toLowerCase() !== username.toLowerCase())
|
2023-04-06 12:59:25 +00:00
|
|
|
throw new UserError('Authentication failed');
|
|
|
|
|
2023-06-21 12:17:25 +00:00
|
|
|
await authCode.destroy(myOptions);
|
2023-04-06 12:59:25 +00:00
|
|
|
};
|
|
|
|
};
|