refs #6427 feat restorePassWordSMS

This commit is contained in:
Javier Segarra 2024-03-20 13:49:49 +01:00
parent 01f23abec9
commit bfc8cda8a2
6 changed files with 120 additions and 5 deletions

View File

@ -0,0 +1,103 @@
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;
}
};
};

View File

@ -10,6 +10,7 @@ module.exports = function(Self) {
require('../methods/vn-user/sign-in')(Self);
require('../methods/vn-user/acl')(Self);
require('../methods/vn-user/recover-password')(Self);
require('../methods/vn-user/recover-passwordSMS')(Self);
require('../methods/vn-user/privileges')(Self);
require('../methods/vn-user/validate-auth')(Self);
require('../methods/vn-user/renew-token')(Self);

View File

@ -106,6 +106,13 @@
"principalId": "$everyone",
"permission": "ALLOW"
},
{
"property": "recoverPasswordSMS",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
},
{
"property": "validateAuth",
"accessType": "EXECUTE",

View File

@ -324,4 +324,9 @@ INSERT INTO mysql.roles_mapping (`User`, `Host`, `Role`, `Admin_option`)
FROM mysql.roles_mapping
WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost;
-- Actualiza los valores de la nueva columna con los valores correspondientes de la tabla userInfo
UPDATE `account`.`user` as `user`
JOIN vn.client `client` ON `user`.id = `client`.id
SET `user`.recoveryPhone = `client`.phone;
FLUSH PRIVILEGES;

View File

@ -3071,10 +3071,6 @@ UPDATE `vn`.`client`
SET phone= 432978106
WHERE id=9;
UPDATE `vn`.`client`
SET phone= 432978106
WHERE id=9;
UPDATE vn.department
SET workerFk = null;

View File

@ -348,5 +348,8 @@
"You are not allowed to modify the alias": "No estás autorizado a modificar el alias",
"The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas",
"This password can only be changed by the user themselves": "Esta contraseña solo puede ser modificada por el propio usuario",
"They're not your subordinate": "No es tu subordinado/a."
"They're not your subordinate": "No es tu subordinado/a.",
"Phone not valid": "Teléfono no es válido",
"User not valid": "Usuario no válido",
"Credentials not valid": "Credenciales no válidas"
}