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

72 lines
2.0 KiB
JavaScript
Raw Normal View History

const isProduction = require('vn-loopback/server/boot/isProduction');
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: [
2024-03-20 12:49:49 +00:00
{
arg: 'userId',
2024-03-20 12:49:49 +00:00
type: 'string',
description: 'The recoveryPhone user\'s',
2024-03-20 12:49:49 +00:00
required: true
},
{
arg: 'verificationCode',
2024-03-20 12:49:49 +00:00
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(userId, verificationCode, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
2024-04-22 05:57:23 +00:00
const user = await Self.findOne({
2024-05-23 19:23:08 +00:00
fields: ['id', 'name', 'email', 'name', 'recoveryPhone'],
where: {
or: [
{id: userId},
{nickname: userId},
{name: userId},
{email: userId},
]
}
2024-04-22 05:57:23 +00:00
});
2024-03-20 12:49:49 +00:00
if (!user) throw new UserError('Credentials not valid');
try {
if (verificationCode) {
await Self.validateCode(user.name, verificationCode);
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-05-23 19:23:08 +00:00
if (isProduction(true))
return {code};
2024-05-23 19:23:08 +00:00
await Self.app.models.Sms.send({req: {accessToken: {userId}}}, +userId, code);
2024-03-20 12:49:49 +00:00
} catch (err) {
if (err.code === 'EMAIL_NOT_FOUND')
return;
else
throw err;
}
};
};