Untitled
unknown
plain_text
9 days ago
7.4 kB
6
Indexable
Never
import { ConflictException, Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { Error, UseCase } from '@ziwig/types'; import { SendEmailService } from 'apps/my-api/src/shared/services/send-email.service'; import { CreateProfessionallUseCase } from 'apps/my-api/src/iam/professional/_api/_use-cases/create-professional/create-professional.use-case'; import { ZgApiLogger } from '@ziwig/nest-core'; import { VerifyUserUseCase } from 'apps/my-api/src/iam/authentification/_api/_use_case/verify-user/verify-code.use-case'; import { RealmConfig } from 'apps/my-api/src/keycloak-auth-guard/keycloak-auth.guard'; import { ConfigService } from '@nestjs/config'; import { ActionTypes, CodeTypes, OutcomeCodeTypes, OutcomeDetailTypes, } from '@ziwig/nest-audit-event-creator'; import { AuthenticationService } from 'apps/my-api/src/iam/authentification/_business'; import { AuthenticationErrors } from 'apps/my-api/src/iam/authentification/_business/authentication.errors'; import { User_KeycloakService, UserErrors, IUser } from '../../../_business'; import { RequestTracesService } from '../../../_business/request-traces.service'; import { CreateUserResponseDTO } from './response.dto'; import { CreateUserRequestDto } from './request.dto'; @Injectable() export class CreateUserUseCase implements UseCase< { body: CreateUserRequestDto; realm: RealmConfig }, Promise<CreateUserResponseDTO> > { constructor( private user_KeycloakService: User_KeycloakService, private sendEmailService: SendEmailService, private createProfessionallUseCase: CreateProfessionallUseCase, private readonly logger: ZgApiLogger, private readonly verifyUserUseCase: VerifyUserUseCase, private readonly configservice: ConfigService, private requestTracesService: RequestTracesService, private authenticationService: AuthenticationService, ) { this.logger.context = CreateUserUseCase.name; } public async run(data: { body: CreateUserRequestDto; realm: RealmConfig; token: string; }): Promise<CreateUserResponseDTO> { //Lang Temporaire variable const lang = 'fr'; const result: any = await this.authenticationService.findDataWithDynamicFilter( ['identifiant_pp'], [data.body.rpps], data.realm.model, ); if (result.isFailure) { const outcome = { codeDisplay: OutcomeCodeTypes.ERROR, }; const errorDetails = { data: { entityIds: [], entityName: 'KEYCLOAK - USERS', }, action: ActionTypes.CREATE, code: CodeTypes.CREATE, }; switch (result.getValue().constructor) { case AuthenticationErrors.MetaNotFoundError: await this.requestTracesService.traceErrorEvent( { ...errorDetails, outcome: { ...outcome, detailDisplay: OutcomeDetailTypes.NO_RESOURCE_FOUND_MATCHING_THE_QUERY, }, }, { userId: '', email: '', }, ); throw new NotFoundException(result.getValue()); default: await this.requestTracesService.traceErrorEvent( { ...errorDetails, outcome: { codeDisplay: OutcomeCodeTypes.FATAL, }, }, { userId: '', email: '', }, ); throw result.getValue() as Error; } } else if (result.getValue() && result.getValue().data?.length > 0) { const existingProfessional = result.getValue().data[0]; let errorDetails; const user = await this.user_KeycloakService.create( data.body, existingProfessional.metadata.id, ); if (user.isFailure) { const outcome = { codeDisplay: OutcomeCodeTypes.ERROR, }; errorDetails = { token: data.token, data: data.body as CreateUserRequestDto, action: ActionTypes.CREATE, code: CodeTypes.CREATE, }; switch (user.getValue().constructor) { case UserErrors.UserAlreadyExistsError: await this.requestTracesService.traceErrorEvent({ ...errorDetails, outcome: { ...outcome, detailDisplay: OutcomeDetailTypes.PARAMETER_IS_NOT_ALLOWED_TO_REPEAT, }, }); throw new ConflictException(user.getValue()); default: await this.requestTracesService.traceErrorEvent({ ...errorDetails, outcome: { codeDisplay: OutcomeCodeTypes.FATAL, }, }); throw user.getValue() as Error; } } const verifyUser = await this.verifyUserUseCase.run({ input: { search: data.body.username }, realm: { realm: data.body.domaine, }, }); const linkInitPassword = `${this.configservice.get('FRONT_URL')}/${ data.realm.realm }/auth/update-credential/init-password/${verifyUser.session_id}`; const site = `${this.configservice.get('FRONT_URL')}/${ data.realm.realm }/auth/login-sat`; const emailData = { user: data.body, emailTemplate: 'user-creation-template.html', subject: "confirmation d'ouverture de compte", email: data.body.email, linkInitPassword, site, lang: lang, }; const sendEmail = await this.sendEmailService.sendEmail(emailData); if (sendEmail.isFailure) { await this.requestTracesService.traceErrorEvent({ token: data.token, data: { entityIds: [], entityName: 'KEYCLOAK - USERS', }, action: ActionTypes.CREATE, code: CodeTypes.CREATE, outcome: { codeDisplay: OutcomeCodeTypes.FATAL, }, }); throw new InternalServerErrorException(sendEmail.getValue() as Error); } this.logger.info('User created successfully', this.run.name); await this.requestTracesService.traceCreatedEvent({ token: data.token, data: { entityIds: [(user.getValue() as IUser).id], entityName: 'KEYCLOAK - USERS', }, }); return CreateUserResponseDTO.fromModel(user.getValue() as IUser); } else { throw new NotFoundException({ code: 'professional_not_found', message: 'professional not found', context: '', error: null, }); } // else if (data.body.isProfessionalCreated === false) { // const createdUser: any = user.getValue(); // const newProfessional = prepareCreateProfessionalByUserIdData( // createdUser.id, // data.body, // ); // await this.createProfessionallUseCase.run({ // body: newProfessional, // deleteKeyloakUser: true, // keycloakUserId: createdUser.id, // domain: data.body.domaine, // token: data.token, // }); // } } }
Leave a Comment