Files
api-AT/src/user/user.service.ts
T
2026-03-17 12:07:26 -05:00

155 lines
3.7 KiB
TypeScript

import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { Response } from 'express';
import { changePasswordDto, CreateUserDto, Login } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Perfil, User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
@InjectRepository(Perfil)
private perfilRepository: Repository<Perfil>,
private jwtService: JwtService,
) { }
async toggleActivo(id: number) {
const usuario = await this.userRepository.findOne({
where: { id_usuario: id }
});
if (!usuario) {
throw new NotFoundException("no se encontro usuario")
}
usuario.activo = usuario.activo === 1 ? 0 : 1;
return this.userRepository.save(usuario);
}
async getactive(id: number) {
const user = await this.userRepository.findOne({
where: { id_usuario: id },
});
if (!user) {
throw new NotFoundException('Usuario no encontrado');
}
user.activo = user.activo === 1 ? 0 : 1;
return this.userRepository.save(user);
}
async findOneByNameandPassword(data: Login): Promise<User> {
const { usuario, password } = data;
const user = await this.userRepository.findOne({
where: { usuario, password },
});
if (user?.activo === 0) {
throw new NotFoundException(`El usuario se encuentra desactivado`);
}
if (!user) {
throw new NotFoundException(`El usuario o la contraseña es incorrecta`);
}
return user;
}
async Login(data: Login, res: Response) {
const user = await this.findOneByNameandPassword(data);
const payload = {
id: user.id_usuario,
usuario: user.nombre,
role: user.perfil.id_perfil,
};
const token = await this.jwtService.signAsync(payload);
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/',
});
return res.json({
message: 'Inicio de sesión exitoso',
access_token: token,
});
}
async findOne(id_usuario: number): Promise<User> {
const user = await this.userRepository.findOne({
where: { id_usuario },
});
if (!user) {
throw new NotFoundException(`Student not found`);
}
return user;
}
async findbyUser(usuario: string) {
const user = await this.userRepository.findOne({
where: { usuario },
});
return user;
}
async create(data: CreateUserDto) {
const { id_perfil, ...rest } = data;
const user = await this.findbyUser(data.usuario);
if (user) {
throw new BadRequestException('User found, change the user ');
}
const perfil = await this.perfilRepository.findOne({
where: { id_perfil },
});
if (!perfil) {
throw new NotFoundException('Perfil not found');
}
const fecha_registro = new Date();
const datauser = { ...rest, perfil, fecha_registro };
const usercreate = this.userRepository.create(datauser);
return this.userRepository.save(usercreate);
}
async changePassword(data: changePasswordDto, id_usuario: number) {
const user = await this.findOneByNameandPassword({
usuario: (await this.findOne(id_usuario)).usuario,
password: data.password,
});
user.password = data.newPassword;
return this.userRepository.save(user);
}
async getAll() {
return this.userRepository.find({select:['id_usuario','nombre','usuario','perfil','activo','password']});
}
async getAllPerfil() {
return this.perfilRepository.find();
}
}
//IO