enhance: permission handling

This commit is contained in:
Julian Krauser 2025-05-16 11:17:02 +02:00
parent b8df454048
commit b778b6faa7

View file

@ -73,6 +73,23 @@ export default class PermissionHelper {
}, false); }, false);
} }
static canAccessSection(permissions: PermissionObject, section: PermissionSection): boolean {
if (permissions?.admin || permissions?.adminByOwner) return true;
if (permissions[section] != undefined) return true;
return false;
}
static canAccessSomeSection(
permissions: PermissionObject,
checks: Array<{
section: PermissionSection;
}>
): boolean {
return checks.reduce<boolean>((prev, curr) => {
return prev || this.canAccessSection(permissions, curr.section);
}, false);
}
static canValue(permissions: PermissionObject, key: string, emptyIfAdmin: boolean = false): string { static canValue(permissions: PermissionObject, key: string, emptyIfAdmin: boolean = false): string {
if (emptyIfAdmin && (permissions.admin || permissions.adminByOwner)) return ""; if (emptyIfAdmin && (permissions.admin || permissions.adminByOwner)) return "";
return permissions?.additional?.[key] ?? ""; return permissions?.additional?.[key] ?? "";
@ -147,6 +164,37 @@ export default class PermissionHelper {
}; };
} }
static sectionAccessPassCheckMiddleware(
section: PermissionSection
): (req: Request, res: Response, next: Function) => void {
return (req: Request, res: Response, next: Function) => {
const permissions = req.permissions;
const isOwner = req.isOwner;
if (isOwner || this.canAccessSection(permissions, section)) {
next();
} else {
throw new ForbiddenRequestException(`missing permission for ${section}.${module}`);
}
};
}
static sectionAccessPassCheckSomeMiddleware(
checks: Array<{ section: PermissionSection }>
): (req: Request, res: Response, next: Function) => void {
return (req: Request, res: Response, next: Function) => {
const permissions = req.permissions;
const isOwner = req.isOwner;
if (isOwner || this.canAccessSomeSection(permissions, checks)) {
next();
} else {
let permissionsToPass = checks.map((c) => `${c.section}`).join(" or ");
throw new ForbiddenRequestException(`missing permission for ${permissionsToPass}`);
}
};
}
static isAdminMiddleware(): (req: Request, res: Response, next: Function) => void { static isAdminMiddleware(): (req: Request, res: Response, next: Function) => void {
return (req: Request, res: Response, next: Function) => { return (req: Request, res: Response, next: Function) => {
const permissions = req.permissions; const permissions = req.permissions;