corrected auth

This commit is contained in:
sdraris 2025-09-09 16:42:27 +02:00
parent bc47dac791
commit 05c1a61090

View File

@ -8,8 +8,9 @@ import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { RegisterDto } from '../user/dto/register.dto';
import { ConfigService } from '@nestjs/config';
import { RoleType, StatutUtilisateurType } from 'src/entities/users.entity';
import { RoleType, StatutUtilisateurType, Users } from 'src/entities/users.entity';
import { LoginDto } from '../user/dto/login.dto';
import { DeepPartial } from 'typeorm';
@Injectable()
export class AuthService {
@ -23,23 +24,12 @@ export class AuthService {
* Génère un access_token et un refresh_token
*/
async generateTokens(userId: string, email: string, role: RoleType) {
const secret = this.configService.get<string>('jwt.secret');
const expiresIn = this.configService.get<string>('jwt.expiresIn');
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(
{ sub: userId, email, role },
{
secret: this.configService.get<string>('jwt.secret'),
expiresIn: this.configService.get<string>('jwt.access_token_expires'),
},
),
this.jwtService.signAsync(
{ sub: userId },
{
secret: this.configService.get<string>('jwt.refresh_token_secret'),
expiresIn: this.configService.get<string>(
'jwt.refresh_token_expires',
),
},
),
this.jwtService.signAsync({ sub: userId, email, role }, { secret, expiresIn }),
this.jwtService.signAsync({ sub: userId }, { secret, expiresIn }),
]);
return {
@ -52,15 +42,23 @@ export class AuthService {
* Connexion utilisateur
*/
async login(dto: LoginDto) {
const user = await this.usersService.findByEmail(dto.email);
try {
const user = await this.usersService.findByEmailOrNull(dto.email);
// Vérification du mot de passe
const isMatch = await bcrypt.compare(dto.password, user.password_hash);
if (!isMatch) {
if (!user) {
throw new UnauthorizedException('Identifiants invalides');
}
const isMatch = await bcrypt.compare(dto.password, user.password_hash);
if (!isMatch) {
throw new UnauthorizedException('Identifiants invalides');
}
return this.generateTokens(user.id, user.email, user.role);
} catch (error) {
console.error('Erreur de connexion :', error);
throw new UnauthorizedException('Identifiants invalides');
}
return this.generateTokens(user.id, user.email, user.role);
}
/**
@ -87,31 +85,29 @@ export class AuthService {
* Inscription utilisateur lambda (parent ou assistante maternelle)
*/
async register(registerDto: RegisterDto) {
// Vérifier si l'email existe déjà
const exists = await this.usersService.findByEmail(registerDto.email).catch(() => null);
const exists = await this.usersService.findByEmailOrNull(registerDto.email);
if (exists) {
throw new ConflictException('Email déjà utilisé');
}
// Filtrer les rôles autorisés
const allowedRoles = new Set<RoleType>([RoleType.PARENT, RoleType.ASSISTANTE_MATERNELLE]);
if (!allowedRoles.has(registerDto.role)) {
registerDto.role = RoleType.PARENT;
}
// Statut par défaut
registerDto.status = StatutUtilisateurType.EN_ATTENTE;
// Création de l'utilisateur (UserService gère le hash)
let user;
try {
user = await this.usersService.create(registerDto);
} catch (error) {
console.error('Erreur pendant la creation du user : ', error);
throw new ConflictException('Impossible de creer le user')
if (!registerDto.consent_photo) {
registerDto.consent_photo_at = null;
} else if (registerDto.consent_photo_at) {
const date = new Date(registerDto.consent_photo_at);
if (isNaN(date.getTime())) {
registerDto.consent_photo_at = null;
}
}
// Génération des tokens
const user = await this.usersService.createUser(registerDto);
const tokens = await this.generateTokens(user.id, user.email, user.role);
return {
@ -126,4 +122,5 @@ export class AuthService {
},
};
}
}