add jwt whit cookie

This commit is contained in:
2025-09-12 20:41:51 -06:00
parent 873f34164f
commit ebec29e9e1
4 changed files with 25 additions and 13 deletions
+3 -3
View File
@@ -10,9 +10,9 @@ async function bootstrap() {
app.useGlobalPipes(new ValidationPipe());
app.enableCors(
// {
// origin: configService.get<string>('Front_URL'),
// }
{
origin: configService.get<string>('Front_URL'),
}
);
await app.listen(process.env.PORT ?? 3000);
+1
View File
@@ -32,3 +32,4 @@ export class ServicioController {
return this.servicioService.remove(+id);
}
}
//IO
+8 -5
View File
@@ -1,4 +1,5 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Request } from '@nestjs/common';
import { Controller, Get, Post, Body, UseGuards, Request, Res } from '@nestjs/common';
import type { Response } from 'express';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { AuthGuard } from '@nestjs/passport';
@@ -7,10 +8,11 @@ import { AuthGuard } from '@nestjs/passport';
export class UserController {
constructor(private readonly userService: UserService) { }
@Post()
Login(@Body() user: CreateUserDto) {
return this.userService.Login(user);
}
@Post()
async Login(@Body() data: CreateUserDto, @Res() res: Response) {
return this.userService.Login(data, res);
}
@UseGuards(AuthGuard('jwt'))
@Get('/validate-token')
@@ -19,3 +21,4 @@ export class UserController {
}
}
//IO
+13 -5
View File
@@ -1,4 +1,5 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Response } from 'express';
import { CreateUserDto } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
@@ -24,20 +25,27 @@ export class UserService {
if (!user) {
throw new NotFoundException(
`El usuario ${usuario} no fue encontrado`,
`El usuario o la contraseña es incorrecta`,
);
}
return user;
}
async Login(data: CreateUserDto): Promise<{ access_token: string }> {
async Login(data: CreateUserDto, res: Response) {
const user = await this.findOneByNameandPassword(data);
const payload = { id: user.id_usuario, usuario: user.usuario };
return {
access_token: await this.jwtService.signAsync(payload),
};
const token = await this.jwtService.signAsync(payload);
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // en dev desactívalo
sameSite: 'strict',
path: '/',
});
return res.json({ message: 'Inicio de sesión exitoso' });
}
}