import { Body, Controller, Header, HttpCode, Post, Res, UseGuards, } from '@nestjs/common'; import type { Response } from 'express'; import { CreateUserDto, CreateUserDtoResponse } from './dto/create-user.dto'; import { AuthDto, UserRole } from './dto/auth.dto'; import { AuthService } from './auth.service'; import { AuthGuard } from './guard/auth.guard'; import { RolesGuard } from './guard/roles.guard'; import { Roles } from './decorator/roles.decorator'; import { ConfigService } from '@nestjs/config'; @Controller('/auth') export class AuthController { constructor( private authService: AuthService, private configService: ConfigService, ) {} @Post('/register') @HttpCode(201) @UseGuards(AuthGuard, RolesGuard) @Roles(UserRole.Admin) registerUser(@Body() data: CreateUserDto): Promise { return this.authService.registerUser(data); } @Post('login') async login( @Body() loginDto: AuthDto, @Res({ passthrough: true }) res: Response, ) { const { accessToken, csrfToken, user } = await this.authService.signIn( loginDto.username, loginDto.password, ); res.cookie('access_token', accessToken, { httpOnly: true, secure: this.configService.get('NODE_ENV') !== 'development', sameSite: 'strict', maxAge: parseInt( this.configService.get('COOKIE_MAX_AGE') || '7200000', 10, ), }); return { user, csrfToken }; } @Post('logout') @HttpCode(200) logout(@Res({ passthrough: true }) res: Response) { res.clearCookie('access_token', { httpOnly: true, secure: this.configService.get('NODE_ENV') !== 'development', sameSite: 'strict', }); return { message: 'Logout berhasil' }; } }