refs #6427 feat: use authCode and validateCode

This commit is contained in:
Javier Segarra 2024-03-26 08:18:20 +01:00
parent dc25912528
commit f70b663ac0
1 changed files with 15 additions and 9 deletions

View File

@ -1,4 +1,5 @@
const UserError = require('vn-loopback/util/user-error');
const authCode = require('../../models/authCode');
const OTP_CHAR = ':';
function original({id, phone}) {
const total = parseInt(phone) + parseInt(id);
@ -72,13 +73,18 @@ module.exports = Self => {
}
});
Self.recoverPasswordSMS = async function(ctx, id, phone, _otp) {
Self.recoverPasswordSMS = async function(ctx, id, phone, _otp, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
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'],
fields: ['id', 'phone', 'email', 'name'],
where: {id, phone}
};
@ -87,18 +93,18 @@ module.exports = Self => {
try {
if (_otp) {
await Self.validateCode(user.name, _otp);
return {
valid: checkOTP(query.where, _otp),
token: await user.accessTokens.create({})
};
}
// 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};
const code = await authCode(user, myOptions);
if (process.env.NODE_ENV != 'production')
await Self.app.models.Sms.send({req: {accessToken: {userId: id}}}, +phone, code);
return {otp: true};
} catch (err) {
if (err.code === 'EMAIL_NOT_FOUND')
return;