From f75bd04736259346889da07d08ec776edb86afa6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 20 Mar 2024 14:11:05 +0100 Subject: [PATCH] refs #6427 perf: restorePasswordSMS --- back/methods/vn-user/recover-passwordSMS.js | 38 ++++++++++++--------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/back/methods/vn-user/recover-passwordSMS.js b/back/methods/vn-user/recover-passwordSMS.js index af9b99f410..3305805c0d 100644 --- a/back/methods/vn-user/recover-passwordSMS.js +++ b/back/methods/vn-user/recover-passwordSMS.js @@ -1,29 +1,29 @@ 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); + const total = parseInt(phone) + parseInt(id); + const value = total.toString().slice(-6); - // 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 + return parseInt(value); // 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) { +function selectOTPMethod() { const otpIndex = Math.floor(Math.random() * Object.keys(OTP_TYPES).length); - const otpType = _otpType ?? Object.keys(OTP_TYPES)[otpIndex]; + return Object.keys(OTP_TYPES)[otpIndex]; +} +function generateOTP(params, _otpType, format = true) { + const otpType = _otpType ?? selectOTPMethod(); const otp = OTP_TYPES[otpType](params); - return formatOTP(otpType, otp); + if (format) return formatOTP({otpType, otp}); + return {otpType, otp}; } -function formatOTP(otpType, otpValue) { - return `${otpType}${OTP_CHAR}${otpValue}`; +function formatOTP({otpType, otp}) { + return `${otpType}${OTP_CHAR}${otp}`; } function checkOTP(params, otp) { @@ -72,7 +72,7 @@ module.exports = Self => { } }); - Self.recoverPasswordSMS = async function(ctx, id, phone, otp) { + 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'); @@ -86,13 +86,19 @@ module.exports = Self => { if (!user) throw new UserError('Credentials not valid'); try { - if (otp) { + if (_otp) { return { - valid: checkOTP(query.where, otp), + valid: checkOTP(query.where, _otp), token: await user.accessTokens.create({}) }; } - return {otp: generateOTP(query.where)}; + // ONLY FOR TESTS + // return {otp: generateOTP(query.where)}; + + // AFTER TESTS + // const otp = generateOTP(query.where, null, false); + // await Self.app.models.Sms.send({req: {accessToken: {userId: id}}}, +phone, formatOTP(otp)); + // return {otp: otp.otpType}; } catch (err) { if (err.code === 'EMAIL_NOT_FOUND') return;