refactor: extract permission to utils
This commit is contained in:
parent
250d69d122
commit
19502acd8a
2 changed files with 49 additions and 28 deletions
|
|
@ -4,6 +4,8 @@ import HttpError from "../interfaces/http-error";
|
|||
import HttpStatus from "../interfaces/http-status";
|
||||
import { RequestWithUser } from "../interfaces/user";
|
||||
import { isSystem } from "../utils/keycloak";
|
||||
import { ExpressionBuilder } from "kysely";
|
||||
import { DB } from "../generated/kysely/types";
|
||||
|
||||
export function branchRelationPermInclude(user: RequestWithUser["user"]) {
|
||||
return {
|
||||
|
|
@ -133,3 +135,47 @@ export function createPermCheck(globalAllow: (user: RequestWithUser["user"]) =>
|
|||
return branch;
|
||||
};
|
||||
}
|
||||
|
||||
export function createQueryPermissionCondition(
|
||||
globalAllow: (user: RequestWithUser["user"]) => boolean,
|
||||
opts?: { alwaysIncludeHead?: boolean },
|
||||
) {
|
||||
return (user: RequestWithUser["user"]) =>
|
||||
({ eb, exists }: ExpressionBuilder<DB, keyof DB>) =>
|
||||
exists(
|
||||
eb
|
||||
.selectFrom("Branch")
|
||||
.leftJoin("BranchUser", "BranchUser.branchId", "Branch.id")
|
||||
.leftJoin("Branch as SubBranch", "SubBranch.headOfficeId", "Branch.id")
|
||||
.leftJoin("BranchUser as SubBranchUser", "SubBranchUser.branchId", "SubBranch.id")
|
||||
.leftJoin("Branch as HeadBranch", "HeadBranch.id", "Branch.id")
|
||||
.leftJoin("BranchUser as HeadBranchUser", "HeadBranchUser.branchId", "HeadBranch.id")
|
||||
.leftJoin("Branch as SubHeadBranch", "SubHeadBranch.headOfficeId", "HeadBranch.id")
|
||||
.leftJoin(
|
||||
"BranchUser as SubHeadBranchUser",
|
||||
"SubHeadBranchUser.branchId",
|
||||
"SubHeadBranch.id",
|
||||
)
|
||||
.where((eb) => {
|
||||
const cond = [
|
||||
eb("BranchUser.userId", "=", user.sub), // NOTE: if user belong to current branch.
|
||||
];
|
||||
|
||||
if (globalAllow?.(user) || opts?.alwaysIncludeHead) {
|
||||
cond.push(
|
||||
eb("SubBranchUser.userId", "=", user.sub), // NOTE: if user belong to branch under current branch.
|
||||
);
|
||||
}
|
||||
|
||||
if (globalAllow(user)) {
|
||||
cond.push(
|
||||
eb("HeadBranchUser.userId", "=", user.sub), // NOTE: if the current branch is under head branch user belong to.
|
||||
eb("SubHeadBranchUser.userId", "=", user.sub), // NOTE: if the current branch is under the same head branch user belong to.
|
||||
);
|
||||
}
|
||||
|
||||
return eb.or(cond);
|
||||
})
|
||||
.select("Branch.id"),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue