import { Inject, Injectable } from "@nestjs/common"; import { validate } from "class-validator"; import { GroupService } from "./group.service"; import { Account } from "../models/account"; import { plainToClass } from "class-transformer"; import { Registration } from "../models/registration"; import * as authentication from "@apihub24/authentication"; @Injectable() export class AccountFactoryService { constructor( @Inject(authentication.APIHUB24_PASSWORD_SERVICE) private readonly passwordService: authentication.IPasswordService, @Inject(GroupService) private readonly groupService: GroupService ) {} /** * create a new Account from a Registration * @param registration a Registration * @returns a new User Account */ async createFromRegistration( registration: authentication.IRegistration ): Promise { let validationErrors = await validate( plainToClass(Registration, registration) ); if (validationErrors?.length) { throw new Error(validationErrors[0].toString()); } const groups = await this.groupService.getBy((x) => registration.groupIds.includes(x.id) ); const account = new Account(); account.accountName = registration.accountName; account.email = registration.email; account.emailVerified = false; account.passwordHash = await this.passwordService.hash( registration.password ); account.active = false; account.groups = groups; validationErrors = await validate(plainToClass(Account, account)); if (validationErrors?.length) { throw new Error(validationErrors[0].toString()); } return account; } }