61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
import {
|
|
IsEnum,
|
|
IsInt,
|
|
IsNotEmpty
|
|
} from "class-validator";
|
|
import { getConnectionManager } from 'typeorm';
|
|
import { PrincipalNotFoundError } from '../../errors/PrincipalErrors';
|
|
import { Permission } from '../entities/Permission';
|
|
import { Principal } from '../entities/Principal';
|
|
import { PermissionAction } from '../enums/PermissionAction';
|
|
import { PermissionTarget } from '../enums/PermissionTargets';
|
|
|
|
/**
|
|
* This classed is used to create a new Permission entity from a json body (post request).
|
|
*/
|
|
export class CreatePermission {
|
|
|
|
/**
|
|
* The new permissions's principal's id.
|
|
*/
|
|
@IsInt()
|
|
@IsNotEmpty()
|
|
principal: number;
|
|
|
|
/**
|
|
* The new permissions's target.
|
|
*/
|
|
@IsNotEmpty()
|
|
@IsEnum(PermissionTarget)
|
|
target: PermissionTarget;
|
|
|
|
/**
|
|
* The new permissions's action.
|
|
*/
|
|
@IsNotEmpty()
|
|
@IsEnum(PermissionAction)
|
|
action: PermissionAction;
|
|
|
|
/**
|
|
* Creates a new Permission entity from this.
|
|
*/
|
|
public async toPermission(): Promise<Permission> {
|
|
let newPermission: Permission = new Permission();
|
|
|
|
newPermission.principal = await this.getPrincipal();
|
|
newPermission.target = this.target;
|
|
newPermission.action = this.action;
|
|
|
|
return newPermission;
|
|
}
|
|
|
|
/**
|
|
* Gets the new permission's principal by it's id.
|
|
*/
|
|
public async getPrincipal(): Promise<Principal> {
|
|
let principal = await getConnectionManager().get().getRepository(Principal).findOne({ id: this.principal })
|
|
if (!principal) { throw new PrincipalNotFoundError(); }
|
|
return principal;
|
|
}
|
|
}
|