import { Controller, Post, Body, UnauthorizedException } from '@nestjs/common'; import { AuthService } from './auth.service'; import { UsersService } from '../users/users.service'; import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'; class LoginDto { username: string; password: string; } class LoginResponse { access_token: string; } class RegisterDto { username: string; email: string; password: string; } @ApiTags('Auth') @Controller('auth') export class AuthController { constructor( private authService: AuthService, private usersService: UsersService, ) {} @ApiOperation({ summary: 'Register new user' }) @ApiBody({ description: 'User registration data', type: RegisterDto, examples: { example1: { summary: 'Typical registration', value: { username: 'john_doe', email: 'john@example.com', password: '123456', }, }, }, }) @ApiResponse({ status: 201, description: 'User created successfully', }) @ApiResponse({ status: 409, description: 'Username already exists', }) @Post('register') async register(@Body() body: RegisterDto) { const existing = await this.usersService.findOneByUsername(body.username); if (existing) { throw new UnauthorizedException('Username already exists'); } return this.usersService.create(body); } @ApiOperation({ summary: 'Login user' }) @ApiBody({ description: 'User login data', type: LoginDto, examples: { example1: { summary: 'Typical login', value: { username: 'john_doe', password: '123456', }, }, }, }) @ApiResponse({ status: 200, description: 'User logged in successfully', type: LoginResponse, }) @ApiResponse({ status: 401, description: 'Invalid username or password', }) @Post('login') async login(@Body() body: LoginDto) { const user = await this.authService.validateUser(body.username, body.password); return this.authService.login(user); } }