import * as argon2 from "argon2"; import { IsEmail, IsOptional, IsPhoneNumber, IsString } from 'class-validator'; import { getConnectionManager } from 'typeorm'; import * as uuid from 'uuid'; import { UsernameOrEmailNeededError } from '../../errors/UserErrors'; import { UserGroupNotFoundError } from '../../errors/UserGroupErrors'; import { User } from '../entities/User'; import { UserGroup } from '../entities/UserGroup'; export class CreateUser { /** * The new user's first name. */ @IsString() firstname: string; /** * The new user's middle name. * Optinal. */ @IsString() @IsOptional() middlename?: string; /** * The new user's last name. */ @IsString() lastname: string; /** * The new user's username. * You have to provide at least one of: {email, username}. */ @IsOptional() @IsString() username?: string; /** * The new user's email address. * You have to provide at least one of: {email, username}. */ @IsEmail() @IsString() @IsOptional() email?: string; /** * The new user's phone number. * Optional */ @IsPhoneNumber("ZZ") @IsOptional() phone?: string; /** * The new user's password. * This will of course not be saved in plaintext :) */ @IsString() password: string; /** * The new user's groups' id(s). * You can provide either one groupId or an array of groupIDs. * Optional. */ @IsOptional() groupId?: number[] | number //TODO: ProfilePics /** * Converts this to a User Entity. */ public async toUser(): Promise { let newUser: User = new User(); if (this.email === undefined && this.username === undefined) { throw new UsernameOrEmailNeededError(); } if (this.groupId) { if (!Array.isArray(this.groupId)) { this.groupId = [this.groupId] } const groupIDs: number[] = this.groupId let errors = 0 const validateusergroups = async () => { let foundgroups = [] for (const g of groupIDs) { const found = await getConnectionManager().get().getRepository(UserGroup).find({ id: g }); if (found.length === 0) { errors++ } else { foundgroups.push(found[0]) } } newUser.groups = foundgroups } await validateusergroups() if (errors !== 0) { throw new UserGroupNotFoundError(); } } newUser.email = this.email newUser.username = this.username newUser.firstname = this.firstname newUser.middlename = this.middlename newUser.lastname = this.lastname newUser.uuid = uuid.v4() newUser.phone = this.phone newUser.password = await argon2.hash(this.password + newUser.uuid); //TODO: ProfilePics return newUser; } }