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

68 lines
2.0 KiB
JavaScript

const UserError = require('vn-loopback/util/user-error');
const isProduction = require('vn-loopback/server/boot/isProduction');
const authCode = require('../../models/authCode');
module.exports = Self => {
Self.remoteMethod('recoverPasswordSMS', {
description: 'Send SMS to the user',
accepts: [
{
arg: 'user',
type: 'string',
description: 'The recoveryPhone user\'s',
required: true
},
{
arg: 'verificationCode',
type: 'string',
description: 'Code tovalidate operation'
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/recoverPasswordSMS`,
verb: 'POST'
}
});
Self.recoverPasswordSMS = async function(user, verificationCode, options) {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const usesEmail = user.indexOf('@') !== -1;
const filter = usesEmail ? {email: user} : {name: user};
const account = await models.VnUser.findOne({
fields: ['id', 'name', 'recoveryPhone'],
where: filter
});
if (!account && !verificationCode) return;
user = account;
if (verificationCode) {
if (!account)
throw new UserError('Invalid or expired verification code');
await Self.validateCode(user.name, verificationCode);
return {
token: await user.accessTokens.create({})
};
}
const code = await authCode(user, myOptions);
if (!isProduction()) {
try {
await Self.app.models.Sms.send(null, +user.recoveryPhone, code, {insert: false});
} catch (e) {
throw new UserError(`We weren't able to send this SMS`);
}
}
return {code: true};
};
};