Files
api-AT/src/user/user.service.ts
T

47 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-09-10 21:03:33 -04:00
import { Injectable, NotFoundException } from '@nestjs/common';
2025-09-12 20:41:51 -06:00
import { Response } from 'express';
2025-09-04 21:04:15 -04:00
import { CreateUserDto } from './dto/create-user.dto';
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 {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
2025-09-18 21:08:19 -06:00
private jwtService: JwtService,
2025-09-10 16:15:36 -06:00
) {}
2025-09-10 16:15:36 -06:00
async findOneByNameandPassword(data: CreateUserDto): Promise<User> {
const { usuario, password } = data;
const user = await this.userRepository.findOne({
2025-09-10 16:15:36 -06:00
where: { usuario, password },
});
if (!user) {
2025-09-18 21:08:19 -06:00
throw new NotFoundException(`El usuario o la contraseña es incorrecta`);
}
return user;
2025-09-04 21:04:15 -04:00
}
2025-09-12 20:41:51 -06:00
async Login(data: CreateUserDto, res: Response) {
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 };
2025-09-12 20:41:51 -06:00
const token = await this.jwtService.signAsync(payload);
2025-09-18 21:08:19 -06:00
res.cookie('token', token, {
2025-09-12 20:41:51 -06:00
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // en dev desactívalo
sameSite: 'strict',
path: '/',
});
return res.json({ message: 'Inicio de sesión exitoso' });
}
2025-09-04 21:04:15 -04:00
}
2025-09-18 21:08:19 -06:00
//IO