forked from Ynov/ptitspas-ynov-back
67 lines
2.4 KiB
TypeScript
67 lines
2.4 KiB
TypeScript
import { Body, Controller, Get, Post, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
|
|
import { LoginDto } from '../user/dto/login.dto';
|
|
import { AuthService } from './auth.service';
|
|
import { Public } from 'src/common/decorators/public.decorator';
|
|
import { RegisterDto } from '../user/dto/register.dto';
|
|
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
|
import { AuthGuard } from 'src/common/guards/auth.guard';
|
|
import type { Request } from 'express';
|
|
import { UserService } from '../user/user.service';
|
|
import { ProfileResponseDto } from '../user/dto/profile_response.dto';
|
|
import { RefreshTokenDto } from '../user/dto/refresh_token.dto';
|
|
|
|
@ApiTags('Authentification')
|
|
@Controller('auth')
|
|
export class AuthController {
|
|
constructor(
|
|
private readonly authService: AuthService,
|
|
private readonly userService: UserService,
|
|
) { }
|
|
|
|
|
|
@Public()
|
|
@ApiOperation({ summary: 'Connexion' })
|
|
@Post('login')
|
|
async login(@Body() dto: LoginDto) {
|
|
return this.authService.login(dto);
|
|
}
|
|
|
|
@Public()
|
|
@Post('register')
|
|
@ApiOperation({ summary: 'Inscription' })
|
|
async register(@Body() dto: RegisterDto) {
|
|
return this.authService.register(dto);
|
|
}
|
|
|
|
@Public()
|
|
@Post('refresh')
|
|
@ApiBearerAuth('refresh_token')
|
|
@ApiResponse({ status: 200, description: 'Nouveaux tokens générés avec succès.' })
|
|
@ApiResponse({ status: 401, description: 'Token de rafraîchissement invalide ou expiré.' })
|
|
@ApiOperation({ summary: 'Rafraichir les tokens' })
|
|
async refresh(@Body() dto: RefreshTokenDto) {
|
|
return this.authService.refreshTokens(dto.refresh_token);
|
|
}
|
|
|
|
@Get('me')
|
|
@UseGuards(AuthGuard)
|
|
@ApiBearerAuth('access-token')
|
|
@ApiOperation({ summary: "Récupérer le profil complet de l'utilisateur connecté" })
|
|
@ApiResponse({ status: 200, type: ProfileResponseDto })
|
|
async getProfile(@Req() req: Request): Promise<ProfileResponseDto> {
|
|
if (!req.user || !req.user.sub) {
|
|
throw new UnauthorizedException('Utilisateur non authentifié');
|
|
}
|
|
const user = await this.userService.findOne(req.user.sub);
|
|
return {
|
|
id: user.id,
|
|
email: user.email,
|
|
role: user.role,
|
|
prenom: user.prenom ?? '',
|
|
nom: user.nom ?? '',
|
|
statut: user.statut,
|
|
};
|
|
}
|
|
}
|
|
|