feat(02-01): AuthModule with Passport strategies, guards, and decorators
- Create LocalStrategy (username/password via argon2) and JwtStrategy (cookie extractor) - Create JwtAuthGuard with @Public() decorator support for route opt-out - Create RolesGuard checking SUPER_ADMIN/ADMIN/USER roles per D-12 - Create AuthService with validateUser, login (30-day httpOnly cookie), logout - Create AuthController with POST /auth/login, POST /auth/logout, GET /auth/me - Create LoginDto with class-validator decorators - Create @Public, @Roles, @CurrentUser decorators - Update main.ts with ValidationPipe, CORS credentials, cookie-parser - Install cookie-parser for httpOnly JWT cookie support
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
Post,
|
||||
Req,
|
||||
Res,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { Request, Response } from 'express';
|
||||
import { AuthService } from './auth.service';
|
||||
import { CurrentUser } from './decorators/current-user.decorator';
|
||||
import { Public } from './decorators/public.decorator';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
/**
|
||||
* POST /auth/login
|
||||
* Validates credentials via Passport local strategy, then issues JWT cookie.
|
||||
*/
|
||||
@Public()
|
||||
@UseGuards(AuthGuard('local'))
|
||||
@Post('login')
|
||||
@HttpCode(200)
|
||||
async login(
|
||||
@Req() req: Request,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
return this.authService.login(req.user, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /auth/logout
|
||||
* Clears the session cookie.
|
||||
*/
|
||||
@Post('logout')
|
||||
@HttpCode(200)
|
||||
logout(@Res({ passthrough: true }) res: Response) {
|
||||
this.authService.logout(res);
|
||||
return { message: 'Logged out' };
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /auth/me
|
||||
* Returns the current user from JWT (session check).
|
||||
*/
|
||||
@Get('me')
|
||||
me(@CurrentUser() user: any) {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user