refactor: use factory function for perm check
This commit is contained in:
parent
9e745ee81c
commit
cbdb4c0e7a
5 changed files with 131 additions and 320 deletions
71
src/services/permission.ts
Normal file
71
src/services/permission.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import prisma from "../db";
|
||||
import HttpError from "../interfaces/http-error";
|
||||
import HttpStatus from "../interfaces/http-status";
|
||||
import { RequestWithUser } from "../interfaces/user";
|
||||
import { isSystem } from "../utils/keycloak";
|
||||
|
||||
export function branchRelationPermInclude(user: RequestWithUser["user"]) {
|
||||
return {
|
||||
headOffice: {
|
||||
include: {
|
||||
branch: { where: { user: { some: { userId: user.sub } } } },
|
||||
user: { where: { userId: user.sub } },
|
||||
},
|
||||
},
|
||||
user: { where: { userId: user.sub } },
|
||||
};
|
||||
}
|
||||
|
||||
export async function getBranchPermissionCheck(user: RequestWithUser["user"], branchId: string) {
|
||||
return await prisma.branch.findUnique({
|
||||
include: {
|
||||
headOffice: {
|
||||
include: {
|
||||
branch: { where: { user: { some: { userId: user.sub } } } },
|
||||
user: { where: { userId: user.sub } },
|
||||
},
|
||||
},
|
||||
user: { where: { userId: user.sub } },
|
||||
},
|
||||
where: { id: branchId },
|
||||
});
|
||||
}
|
||||
|
||||
export function createPermCheck(globalAllow: (user: RequestWithUser["user"]) => boolean) {
|
||||
return async (
|
||||
user: RequestWithUser["user"],
|
||||
branch: Awaited<ReturnType<typeof getBranchPermissionCheck>> | string,
|
||||
) => {
|
||||
if (typeof branch === "string") {
|
||||
branch = await getBranchPermissionCheck(user, branch);
|
||||
}
|
||||
|
||||
if (!branch) {
|
||||
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
|
||||
}
|
||||
|
||||
if (!isSystem(user)) {
|
||||
if (!globalAllow(user) && branch.user.length === 0) {
|
||||
throw new HttpError(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"You do not have permission to perform this action.",
|
||||
"noPermission",
|
||||
);
|
||||
} else {
|
||||
if (
|
||||
(branch.user.length === 0 && !branch.headOffice) ||
|
||||
(branch.headOffice &&
|
||||
branch.headOffice.user.length === 0 &&
|
||||
branch.headOffice.branch.length === 0)
|
||||
) {
|
||||
throw new HttpError(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"You do not have permission to perform this action.",
|
||||
"noPermission",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return branch;
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue