hospital-log/backend/api/src/modules/auth/auth.controller.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

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, AuthDtoResponse, 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')
@Header('Content-Type', 'application/json')
@HttpCode(201)
@UseGuards(AuthGuard, RolesGuard)
@Roles(UserRole.Admin)
registerUser(@Body() data: CreateUserDto): Promise<CreateUserDtoResponse> {
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<string>('NODE_ENV') !== 'development',
sameSite: 'strict',
maxAge: 3600000,
});
return { user, csrfToken };
}
}