45 lines
1.4 KiB
JavaScript
45 lines
1.4 KiB
JavaScript
const { Op } = require('sequelize');
|
|
const { crearTokenUsuario } = require('../../middleware/autentificacion');
|
|
const helperPath = '../../helper';
|
|
const { comparar } = require(`${helperPath}/encriptar`);
|
|
const validar = require(`${helperPath}/validar`);
|
|
const dbPath = '../../db/tablas';
|
|
const Carrera = require(`${dbPath}/Carrera`);
|
|
const Usuario = require(`${dbPath}/Usuario`);
|
|
const TipoUsuario = require(`${dbPath}/TipoUsuario`);
|
|
|
|
const login = async (body) => {
|
|
const usuario = validar.validarNumeroCuenta(body.usuario);
|
|
const password = validar.validarAlfanumerico(
|
|
body.password,
|
|
'contraseña',
|
|
false,
|
|
20
|
|
);
|
|
|
|
return Usuario.findOne({
|
|
where: { usuario, password: { [Op.ne]: null } },
|
|
attributes: ['idUsuario', 'password', 'activo'],
|
|
})
|
|
.then((res) => {
|
|
if (!res) throw new Error('No existe este usuario.');
|
|
if (!res.activo) throw new Error('Este cuenta se encuentra desactivada.');
|
|
if (!comparar(password, res.password))
|
|
throw new Error('La contraseña es incorrecta.');
|
|
return Usuario.findOne({
|
|
where: { usuario },
|
|
include: [{ model: TipoUsuario }, { model: Carrera }],
|
|
attributes: ['idUsuario', 'usuario', 'nombre', 'multa', 'activo'],
|
|
});
|
|
})
|
|
.then((res) => ({
|
|
Usuario: res,
|
|
token: crearTokenUsuario({
|
|
idUsuario: res.idUsuario,
|
|
idTipoUsuario: res.TipoUsuario.idTipoUsuario,
|
|
}),
|
|
}));
|
|
};
|
|
|
|
module.exports = login;
|