51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import { Inject, Injectable } from "@nestjs/common";
|
|
import { validate } from "class-validator";
|
|
import { GroupService } from "./group.service";
|
|
import * as passwordService from "../contracts/services/password.service";
|
|
import { IRegistration } from "../contracts/models/registration";
|
|
import { IAccount } from "../contracts/models/account";
|
|
import { Account } from "../models/account";
|
|
import { plainToClass } from "class-transformer";
|
|
import { Registration } from "../models/registration";
|
|
|
|
@Injectable()
|
|
export class AccountFactoryService {
|
|
constructor(
|
|
@Inject("@apihub24/password_service")
|
|
private readonly passwordService: passwordService.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: IRegistration): Promise<IAccount> {
|
|
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(account);
|
|
if (validationErrors?.length) {
|
|
throw new Error(validationErrors[0].toString());
|
|
}
|
|
return account;
|
|
}
|
|
}
|