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

101 lines
2.8 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-17 20:19:58 -06:00
const payload = {
idUser: user.id_usuario,
username: user.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-18 16:53:53 -06:00
async update(userId, updateUserDto) {
return await this.userRepository.update(userId, updateUserDto);
}
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-05 14:35:05 -06:00
}