salix/back/methods/vn-user/recover-passwordSMS.js

80 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-03-20 12:49:49 +00:00
const UserError = require('vn-loopback/util/user-error');
const authCode = require('../../models/authCode');
2024-03-20 12:49:49 +00:00
module.exports = Self => {
Self.remoteMethod('recoverPasswordSMS', {
description: 'Send SMS to the user',
accepts: [
{
arg: 'ctx',
type: 'Object',
http: {source: 'context'}
},
{
arg: 'id',
type: 'string',
description: 'The user id',
required: true
},
{
arg: 'phone',
type: 'string',
description: 'The phone user\'s recovery',
2024-03-20 12:49:49 +00:00
required: true
},
{
arg: 'otp',
type: 'string',
description: 'Code tovalidate operation'
2024-03-20 12:49:49 +00:00
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/recoverPasswordSMS`,
verb: 'POST'
}
});
Self.recoverPasswordSMS = async function(ctx, id, phone, _otp, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
2024-03-20 12:49:49 +00:00
const usesPhone = new RegExp(/([+]\d{2})?\d{9}/, 'g').test(+phone);
if (!usesPhone) throw new UserError('Phone not valid');
let query = {
fields: ['id', 'phone', 'email', 'name'],
2024-03-20 12:49:49 +00:00
where: {id, phone}
};
const user = await Self.findOne(query);
if (!user) throw new UserError('Credentials not valid');
try {
2024-03-20 13:11:05 +00:00
if (_otp) {
await Self.validateCode(user.name, _otp);
2024-03-20 12:49:49 +00:00
return {
token: await user.accessTokens.create({})
};
}
2024-03-20 13:11:05 +00:00
const code = await authCode(user, myOptions);
2024-03-26 07:27:44 +00:00
if (process.env.NODE_ENV === 'production')
await Self.app.models.Sms.send({req: {accessToken: {userId: id}}}, +phone, code);
return {otp: true};
2024-03-20 12:49:49 +00:00
} catch (err) {
if (err.code === 'EMAIL_NOT_FOUND')
return;
else
throw err;
}
};
};