import { ForbiddenException, Injectable, NotFoundException } from "@nestjs/common"; import { InjectRepository } from "@nestjs/typeorm"; import { RoleType, Users } from "src/entities/users.entity"; import { Repository } from "typeorm"; import { CreateUserDto } from "./dto/create_user.dto"; import * as bcrypt from 'bcrypt'; import { UpdateUserDto } from "./dto/update_user.dto"; @Injectable() export class UserService { constructor( @InjectRepository(Users) private readonly usersRepository: Repository ) { } //Creation utilisateur async create(dto: CreateUserDto, currentUser?: Users): Promise { //Securiser les roles if (!currentUser || currentUser.role !== RoleType.SUPER_ADMIN) { dto.role = RoleType.PARENT; //Forcer le role parent si pas super admin } //Hash mot de passe const salt = await bcrypt.genSalt(); const password_hash = await bcrypt.hash(dto.password, salt); const user = this.usersRepository.create({ email: dto.email, password_hash, first_name: dto.first_name, last_name: dto.last_name, role: dto.role, status: dto.status, gender: dto.gender, phone: dto.phone, address: dto.address, photo_url: dto.photo_url, consent_photo: dto.consent_photo ?? false, consent_photo_at: dto.consent_photo_at ? new Date(dto.consent_photo_at) : undefined, must_change_password: dto.must_change_password ?? false }) return this.usersRepository.save(user); } //Lister tous les utilisateurs async findAll(): Promise { return this.usersRepository.find(); } async findOneBy(where: Partial) { return this.usersRepository.findOne( { where } ) } //Trouver utilisateur par ID async findOne(id: string): Promise { const user = await this.usersRepository.findOne({ where: { id } }); if (!user) { throw new NotFoundException('Utilisateur introuvable'); } return user; } //Trouver utilisateur par email async findByEmail(email: string): Promise { const user = await this.usersRepository.findOne({ where: { email } }); if (!user) { throw new NotFoundException('Utilisateur introuvable'); } return user; } //Mettre a jour un utilisateur async update(id: string, dto: UpdateUserDto, currentUser: Users): Promise { const user = await this.findOne(id); //Tant que pas super_admin interdir changement de role if (dto.role && currentUser.role !== RoleType.SUPER_ADMIN) { throw new ForbiddenException('Acces reserve aux super admins'); } //Gestion de changement mot de passe if (dto.password) { const salt = await bcrypt.genSalt(); user.password_hash = await bcrypt.hash(dto.password, salt); delete (dto as any).password; } Object.assign(user, dto); return this.usersRepository.save(user); } //Supprimer un utilisateur async remove(id: string): Promise { const result = await this.usersRepository.delete(id); if (result.affected === 0) { throw new NotFoundException('Utilisateur introuvable'); } } }