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

104 lines
2.9 KiB
JavaScript
Raw Normal View History

2024-03-20 12:49:49 +00:00
const UserError = require('vn-loopback/util/user-error');
const OTP_CHAR = ':';
function original({id, phone}) {
// Suma el número de teléfono y el número aleatorio
let suma = parseInt(phone) + parseInt(id);
// Convierte la suma a una cadena y toma solo los últimos 6 dígitos
let resultado = suma.toString().slice(-6);
// Devuelve los últimos 6 dígitos
return parseInt(resultado); // Devolvemos un número entero, no una cadena
}
function reverse(params) {
const _original = original(params);
return parseInt(_original.toString().split('').reverse().join(''));
}
function generateOTP(params, _otpType) {
const otpIndex = Math.floor(Math.random() * Object.keys(OTP_TYPES).length);
const otpType = _otpType ?? Object.keys(OTP_TYPES)[otpIndex];
const otp = OTP_TYPES[otpType](params);
return formatOTP(otpType, otp);
}
function formatOTP(otpType, otpValue) {
return `${otpType}${OTP_CHAR}${otpValue}`;
}
function checkOTP(params, otp) {
const [otpType, value] = otp.split(OTP_CHAR);
return generateOTP(params, otpType) === formatOTP(otpType, value);
}
const OTP_TYPES = {
// 'A': original,
'B': reverse,
};
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 user name or email',
required: true
},
{
arg: 'otp',
type: 'string',
description: 'The directory for mail'
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/recoverPasswordSMS`,
verb: 'POST'
}
});
Self.recoverPasswordSMS = async function(ctx, id, phone, otp) {
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'],
where: {id, phone}
};
const user = await Self.findOne(query);
if (!user) throw new UserError('Credentials not valid');
try {
if (otp) {
return {
valid: checkOTP(query.where, otp),
token: await user.accessTokens.create({})
};
}
return {otp: generateOTP(query.where)};
} catch (err) {
if (err.code === 'EMAIL_NOT_FOUND')
return;
else
throw err;
}
};
};