69 lines
2.1 KiB
TypeScript
69 lines
2.1 KiB
TypeScript
import * as argon2 from "argon2";
|
|
import { IsEmail, IsOptional, IsPhoneNumber, IsString, IsUUID } from 'class-validator';
|
|
import { getConnectionManager } from 'typeorm';
|
|
import * as uuid from 'uuid';
|
|
import { UserGroupNotFoundError, UsernameOrEmailNeededError } from '../../errors/UserErrors';
|
|
import { User } from '../entities/User';
|
|
import { UserGroup } from '../entities/UserGroup';
|
|
|
|
export class CreateUser {
|
|
@IsString()
|
|
firstname: string;
|
|
@IsString()
|
|
middlename?: string;
|
|
@IsOptional()
|
|
@IsString()
|
|
username?: string;
|
|
@IsPhoneNumber("ZZ")
|
|
@IsOptional()
|
|
phone?: string;
|
|
@IsString()
|
|
password: string;
|
|
@IsString()
|
|
lastname: string;
|
|
@IsEmail()
|
|
@IsString()
|
|
email?: string;
|
|
@IsOptional()
|
|
groupId?: number[] | number
|
|
@IsUUID("4")
|
|
uuid: string;
|
|
|
|
public async toUser(): Promise<User> {
|
|
let newUser: User = new User();
|
|
|
|
if (this.email === undefined && this.username === undefined) {
|
|
throw new UsernameOrEmailNeededError();
|
|
}
|
|
|
|
if (this.groupId) {
|
|
if (Array.isArray(this.groupId)) {
|
|
let found_groups = []
|
|
this.groupId.forEach(async (g) => {
|
|
const foundGroup = await getConnectionManager().get().getRepository(UserGroup).find({ id: g });
|
|
if (foundGroup) {
|
|
found_groups.push(foundGroup)
|
|
} else {
|
|
throw new UserGroupNotFoundError();
|
|
}
|
|
});
|
|
newUser.groups = found_groups
|
|
} else {
|
|
newUser.groups = await getConnectionManager().get().getRepository(UserGroup).find({ id: this.groupId });
|
|
}
|
|
}
|
|
|
|
const new_uuid = uuid.v4()
|
|
|
|
newUser.email = this.email
|
|
newUser.username = this.username
|
|
newUser.firstname = this.firstname
|
|
newUser.middlename = this.middlename
|
|
newUser.lastname = this.lastname
|
|
newUser.uuid = new_uuid
|
|
newUser.password = await argon2.hash(this.password + new_uuid);
|
|
|
|
console.log(newUser)
|
|
return newUser;
|
|
}
|
|
} |