2025-09-10 21:03:33 -04:00
|
|
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
2025-09-04 21:04:15 -04:00
|
|
|
import { CreateUserDto } from './dto/create-user.dto';
|
2025-09-09 21:19:17 -04:00
|
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
|
|
|
import { User } from './entities/user.entity';
|
|
|
|
|
import { Repository } from 'typeorm';
|
2025-09-10 21:03:33 -04:00
|
|
|
import { JwtService } from '@nestjs/jwt';
|
2025-09-04 21:04:15 -04:00
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class UserService {
|
2025-09-09 21:19:17 -04:00
|
|
|
constructor(
|
|
|
|
|
@InjectRepository(User)
|
|
|
|
|
private userRepository: Repository<User>,
|
2025-09-10 21:03:33 -04:00
|
|
|
|
|
|
|
|
private jwtService: JwtService
|
2025-09-09 21:19:17 -04:00
|
|
|
) { }
|
|
|
|
|
|
2025-09-10 21:03:33 -04:00
|
|
|
async findOneByNameandPassword(data: CreateUserDto): Promise<User> {
|
2025-09-04 21:04:15 -04:00
|
|
|
|
2025-09-10 16:39:44 -04:00
|
|
|
const { usuario, password } = data
|
2025-09-09 21:19:17 -04:00
|
|
|
|
|
|
|
|
const user = await this.userRepository.findOne({
|
2025-09-10 21:03:33 -04:00
|
|
|
where: { usuario, password }
|
2025-09-09 21:19:17 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
throw new NotFoundException(
|
2025-09-10 16:39:44 -04:00
|
|
|
`El usuario ${usuario} no fue encontrado`,
|
2025-09-09 21:19:17 -04:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return user;
|
2025-09-04 21:04:15 -04:00
|
|
|
}
|
|
|
|
|
|
2025-09-10 21:03:33 -04:00
|
|
|
async Login(data: CreateUserDto): Promise<{ access_token: string }> {
|
2025-09-10 16:39:44 -04:00
|
|
|
const user = await this.findOneByNameandPassword(data);
|
2025-09-10 21:03:33 -04:00
|
|
|
|
|
|
|
|
const payload = { id: user.id_usuario, usuario: user.usuario };
|
|
|
|
|
return {
|
|
|
|
|
access_token: await this.jwtService.signAsync(payload),
|
|
|
|
|
};
|
2025-09-09 21:19:17 -04:00
|
|
|
}
|
|
|
|
|
|
2025-09-04 21:04:15 -04:00
|
|
|
}
|