feat: permission check employee

This commit is contained in:
Methapon Metanipat 2024-09-06 10:54:17 +07:00
parent 16d640f293
commit 806968e3dd
4 changed files with 142 additions and 3 deletions

View file

@ -0,0 +1,70 @@
import express from "express";
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";
export function permissionCheck(globalAllow: (user: RequestWithUser["user"]) => boolean) {
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;
const employee = await prisma.employee.findFirst({
where: { id: employeeId },
include: {
customerBranch: {
include: {
customer: {
include: {
registeredBranch: {
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
},
},
},
},
},
},
});
if (!employee) {
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.headOffice && _branch.headOffice.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",
);
}
}
}
}
next();
};
}