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

69 lines
1.9 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: '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'
}
});
2024-04-22 05:57:23 +00:00
Self.recoverPasswordSMS = async function(id, phone, otp, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
2024-04-22 05:57:23 +00:00
const user = await Self.findOne({
fields: ['id', 'recoveryPhone', 'email', 'name'],
where: {id, recoveryPhone: phone}
});
2024-03-20 12:49:49 +00:00
if (!user) throw new UserError('Credentials not valid');
try {
2024-04-22 05:57:23 +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;
}
};
};