salix/back/methods/vn-user/validate-auth.js

67 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2023-04-06 12:59:25 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
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) => {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
2023-06-21 12:17:25 +00:00
const token = Self.validateLogin(username, password);
2023-06-21 12:17:25 +00:00
await Self.validateCode(username, code, myOptions);
return token;
};
2023-06-21 12:17:25 +00:00
Self.validateCode = async(username, code, myOptions) => {
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-04-06 12:59:25 +00:00
if (user.name !== username)
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
};
};