Files
api_directorio/src/auth/auth.service.ts
T

154 lines
4.0 KiB
TypeScript
Raw Normal View History

2024-06-17 20:19:58 -06:00
import {
HttpException,
Inject,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
2024-06-05 14:35:05 -06:00
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
2024-06-11 19:58:36 -06:00
import { registerDto } from './dto/registerDto.dto';
2024-06-11 15:14:05 -06:00
import { User } from 'src/users/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
2024-06-17 20:19:58 -06:00
import { hash } from 'bcrypt';
2024-06-11 15:14:05 -06:00
import { compare } from 'bcryptjs';
2024-06-12 11:40:20 -06:00
import { ConfigService } from '@nestjs/config';
2024-06-11 15:14:05 -06:00
2024-06-05 14:35:05 -06:00
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
2024-06-11 15:14:05 -06:00
private jwtService: JwtService,
2024-06-17 20:19:58 -06:00
private configService: ConfigService,
@InjectRepository(User) private userRepository: Repository<User>,
2024-06-05 14:35:05 -06:00
) {}
2024-06-16 16:51:45 -06:00
//register users
2024-06-17 20:19:58 -06:00
async register(data: registerDto) {
2024-06-18 16:24:50 -06:00
const { usuario, contraseña} = data;
2024-06-11 19:58:36 -06:00
2024-06-17 20:19:58 -06:00
if (await this.usersService.findOne(usuario)) {
throw new HttpException('User already exist', 403);
2024-06-11 15:14:05 -06:00
}
2024-06-16 16:51:45 -06:00
const hashedpassword = await hash(contraseña, 10);
2024-06-11 15:14:05 -06:00
2024-06-17 20:19:58 -06:00
data = { ...data, contraseña: hashedpassword };
return this.userRepository.save(this.userRepository.create(data));
2024-06-11 15:14:05 -06:00
}
2024-06-16 16:51:45 -06:00
//singin
2024-06-11 15:14:05 -06:00
async signIn(data: registerDto) {
2024-06-17 20:19:58 -06:00
const { usuario, contraseña } = data;
2024-06-16 16:51:45 -06:00
const user = await this.usersService.findOne(usuario);
2024-06-13 15:12:24 -06:00
if (!user) {
2024-06-14 12:59:18 -06:00
throw new UnauthorizedException('Invalid name');
2024-06-13 15:12:24 -06:00
}
2024-06-11 15:14:05 -06:00
2024-06-17 20:19:58 -06:00
const checkPassword = await compare(contraseña, user.contraseña);
2024-06-11 15:14:05 -06:00
if (!checkPassword) {
2024-06-14 12:59:18 -06:00
throw new UnauthorizedException('Invalid password');
2024-06-05 14:35:05 -06:00
}
2024-06-24 16:12:23 -06:00
2024-06-17 20:19:58 -06:00
const payload = {
2024-06-25 20:11:55 -06:00
id_usuario: user.id_usuario,
2024-06-25 22:03:37 -06:00
usuario: user.usuario,
id_tipo_usuario: user.id_tipo_usuario,
2024-06-05 14:35:05 -06:00
};
2024-06-11 15:14:05 -06:00
const token = this.jwtService.sign(payload);
2024-06-17 20:19:58 -06:00
await this.usersService.updateTokenAndDates(
user.id_usuario,
token,
new Date(),
new Date(Date.now() + 3600 * 1000),
);
2024-06-07 13:46:18 -06:00
2024-06-17 20:19:58 -06:00
return { token: token };
2024-06-07 13:46:18 -06:00
}
2024-06-19 12:49:28 -06:00
//update user
async update(userId, data:registerDto) {
2024-06-18 17:20:39 -06:00
2024-06-19 12:49:28 -06:00
const{contraseña}=data;
2024-06-18 17:20:39 -06:00
if(contraseña){
const hashedpassword = await hash(contraseña, 10);
2024-06-19 12:49:28 -06:00
data = {...data,contraseña:hashedpassword};
2024-06-18 17:20:39 -06:00
}
2024-06-19 12:49:28 -06:00
return await this.userRepository.update(userId, data);
2024-06-18 16:53:53 -06:00
}
2024-06-07 13:46:18 -06:00
2024-06-18 16:53:53 -06:00
async remove(userId: number): Promise<void> {
await this.userRepository.delete(userId);
}
2024-06-07 13:46:18 -06:00
2024-06-16 16:51:45 -06:00
//validate tojen of users
2024-06-12 11:40:20 -06:00
async validateToken(token: string): Promise<User> {
try {
const decoded = this.jwtService.verify(token, {
secret: this.configService.get<string>('JWT_SECRET'),
});
//verify JWT's username with DB's username
const user = await this.usersService.findOne(decoded.username);
if (!user) {
throw new UnauthorizedException('Invalid token');
}
2024-06-14 11:05:41 -06:00
//verify JWT hasn't expired
2024-06-12 11:40:20 -06:00
const currentTime = Math.floor(Date.now() / 1000);
if (decoded.exp < currentTime) {
throw new UnauthorizedException('Token has expired');
}
2024-06-14 11:05:41 -06:00
2024-06-12 11:40:20 -06:00
return user;
} catch (error) {
throw new UnauthorizedException('validation token failed');
}
}
2024-06-26 13:31:33 -06:00
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
2024-07-03 14:55:06 -06:00
async findAllPaginated(
page: number,
limit: number,
filters: any
): Promise<{ usuarios: User[], total: number, totalPages: number }> {
const query = this.userRepository.createQueryBuilder('usuario');
if (filters.nombre) {
query.andWhere('usuario.nombre LIKE :nombre', { nombre: `%${filters.nombre}%` });
}
if (filters.id_tipo_usuario) {
query.andWhere('usuario.id_tipo_usuario = :id_tipo_usuario', { id_tipo_usuario: filters.id_tipo_usuario });
}
const [usuarios, total] = await query
.skip((page - 1) * limit)
.take(limit)
.orderBy('usuario.nombre', 'ASC')
.getManyAndCount();
const totalPages = Math.ceil(total / limit);
return { usuarios, total, totalPages };
}
2024-06-26 13:31:33 -06:00
async profile(id_usuario: number) {
const user = await this.userRepository.findOne({
where: { id_usuario },
});
if (!user) {
throw new HttpException('user not found', 404);
}
return user;
}
2024-06-05 14:35:05 -06:00
}