forked from Shared/esg
70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
|
|
import {
|
|
ApiBearerAuth,
|
|
ApiOperation,
|
|
ApiResponse,
|
|
ApiTags,
|
|
} from '@nestjs/swagger';
|
|
import { Request } from 'express';
|
|
import { AuthService } from './auth.service';
|
|
import { CurrentUser } from './decorators/current-user.decorator';
|
|
import { LoginDto } from './dto/login.dto';
|
|
import { RefreshTokenDto } from './dto/refresh-token.dto';
|
|
import { AuthTokensDto } from './dto/auth-tokens.dto';
|
|
import { ProfileDto } from './dto/profile.dto';
|
|
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
|
import { AuthenticatedUser } from './interfaces/authenticated-user.interface';
|
|
|
|
@ApiTags('Auth')
|
|
@Controller('auth')
|
|
export class AuthController {
|
|
constructor(private readonly authService: AuthService) {}
|
|
|
|
@Post('login')
|
|
@ApiOperation({ summary: 'Login with username and password' })
|
|
@ApiResponse({ status: 200, type: AuthTokensDto })
|
|
@ApiResponse({ status: 401, description: 'Invalid credentials' })
|
|
@ApiResponse({ status: 403, description: 'Inactive or blocked account' })
|
|
async login(@Body() dto: LoginDto, @Req() req: Request): Promise<AuthTokensDto> {
|
|
return this.authService.login(dto, {
|
|
ip: req.ip,
|
|
userAgent: req.headers['user-agent'],
|
|
});
|
|
}
|
|
|
|
@Post('refresh')
|
|
@ApiOperation({ summary: 'Refresh access token' })
|
|
@ApiResponse({ status: 200, type: AuthTokensDto })
|
|
async refresh(@Body() dto: RefreshTokenDto, @Req() req: Request): Promise<AuthTokensDto> {
|
|
return this.authService.refresh(dto.refreshToken, {
|
|
ip: req.ip,
|
|
userAgent: req.headers['user-agent'],
|
|
});
|
|
}
|
|
|
|
@Post('logout')
|
|
@UseGuards(JwtAuthGuard)
|
|
@ApiBearerAuth()
|
|
@ApiOperation({ summary: 'Logout and invalidate refresh token' })
|
|
@ApiResponse({ status: 200, description: 'Logged out successfully' })
|
|
async logout(
|
|
@CurrentUser() user: AuthenticatedUser,
|
|
@Req() req: Request,
|
|
): Promise<{ message: string }> {
|
|
await this.authService.logout(user.id, {
|
|
ip: req.ip,
|
|
userAgent: req.headers['user-agent'],
|
|
});
|
|
return { message: 'Logged out successfully' };
|
|
}
|
|
|
|
@Get('profile')
|
|
@UseGuards(JwtAuthGuard)
|
|
@ApiBearerAuth()
|
|
@ApiOperation({ summary: 'Get current user profile' })
|
|
@ApiResponse({ status: 200, type: ProfileDto })
|
|
async profile(@CurrentUser() user: AuthenticatedUser): Promise<ProfileDto> {
|
|
return this.authService.getProfile(user.id);
|
|
}
|
|
}
|