diff --git a/src/middlewares/employee.ts b/src/middlewares/employee.ts index 87580cc..748d3fc 100644 --- a/src/middlewares/employee.ts +++ b/src/middlewares/employee.ts @@ -3,9 +3,11 @@ import { RequestWithUser } from "../interfaces/user"; import prisma from "../db"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; -import { isSystem } from "../utils/keycloak"; +import { branchRelationPermInclude, createPermCheck } from "../services/permission"; export function permissionCheck(globalAllow: (user: RequestWithUser["user"]) => boolean) { + const checker = createPermCheck(globalAllow); + return async (req: RequestWithUser, _res: express.Response, next: express.NextFunction) => { if ("employeeId" in req.params && typeof req.params.employeeId === "string") { const employeeId = req.params.employeeId; @@ -17,23 +19,7 @@ export function permissionCheck(globalAllow: (user: RequestWithUser["user"]) => customer: { include: { registeredBranch: { - include: { - user: { - where: { userId: req.user.sub }, - }, - branch: { - where: { - user: { - some: { userId: req.user.sub }, - }, - }, - include: { - user: { - where: { userId: req.user.sub }, - }, - }, - }, - }, + include: branchRelationPermInclude(req.user), }, }, }, @@ -46,28 +32,7 @@ export function permissionCheck(globalAllow: (user: RequestWithUser["user"]) => throw new HttpError(HttpStatus.BAD_REQUEST, "Employee cannot be found.", "employeeBadReq"); } - if (!isSystem(req.user)) { - const _branch = employee.customerBranch.customer.registeredBranch; - const affilationBranch = _branch && _branch.user.length !== 0; - const affilationHeadBranch = _branch && _branch.branch.every((v) => v.user.length !== 0); - if (!globalAllow(req.user)) { - if (!affilationBranch) { - throw new HttpError( - HttpStatus.FORBIDDEN, - "You do not have permission to perform this action.", - "noPermission", - ); - } - } else { - if (!affilationBranch && !affilationHeadBranch) { - throw new HttpError( - HttpStatus.FORBIDDEN, - "You do not have permission to perform this action.", - "noPermission", - ); - } - } - } + await checker(req.user, employee.customerBranch.customer.registeredBranch); } next(); };