refactor: use factory function for perm check

This commit is contained in:
Methapon Metanipat 2024-09-09 14:40:18 +07:00
parent 9e745ee81c
commit cbdb4c0e7a
5 changed files with 131 additions and 320 deletions

View file

@ -21,6 +21,7 @@ import { RequestWithUser } from "../interfaces/user";
import minio from "../services/minio";
import { isSystem } from "../utils/keycloak";
import { deleteFile, fileLocation, listFile } from "../utils/minio";
import { createPermCheck } from "../services/permission";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
@ -101,48 +102,7 @@ type BranchUpdate = {
}[];
};
async function permissionCheck(user: RequestWithUser["user"], branchId: string) {
const record = 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 },
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
}
if (!isSystem(user)) {
if (!globalAllow(user) && record.user.length === 0) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
} else {
if (
(record.user.length === 0 && !record.headOffice) ||
(record.headOffice &&
record.headOffice.user.length === 0 &&
record.headOffice.branch.length === 0)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
}
}
return record;
}
const permissionCheck = createPermCheck(globalAllow);
@Route("api/v1/branch")
@Tags("Branch")

View file

@ -17,6 +17,7 @@ import prisma from "../db";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "../interfaces/user";
import { branchRelationPermInclude, createPermCheck } from "../services/permission";
const MANAGE_ROLES = ["system", "head_of_admin", "admin", "branch_manager"];
@ -65,6 +66,8 @@ async function userBranchCodeGen(branch: Branch, user: User[]) {
);
}
const permissionCheck = createPermCheck(globalAllow);
@Route("api/v1/branch/{branchId}/manager")
@Tags("Branch User")
export class BranchManagerUserController extends Controller {
@ -185,30 +188,27 @@ export class BranchUserController extends Controller {
) {
const [branch, user] = await prisma.$transaction([
prisma.branch.findUnique({
include: {
user: {
where: { userId: req.user.sub },
},
},
include: branchRelationPermInclude(req.user),
where: { id: branchId },
}),
prisma.user.findMany({
include: { branch: true },
include: {
branch: {
include: {
branch: { include: branchRelationPermInclude(req.user) },
},
},
},
where: { id: { in: body.user } },
}),
]);
if (
!globalAllow(req.user) &&
branch?.createdByUserId !== req.user.sub &&
!branch?.user.find((v) => v.userId === req.user.sub)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
await permissionCheck(req.user, branch);
await Promise.all(
user.map(async (u) => {
await Promise.all(u.branch.map(async (b) => await permissionCheck(req.user, b.branch)));
}),
);
if (!branch) {
throw new HttpError(HttpStatus.BAD_REQUEST, "Branch cannot be found.", "branchBadReq");
@ -250,25 +250,11 @@ export class BranchUserController extends Controller {
@Body() body: BranchUserBody,
) {
const branch = await prisma.branch.findUnique({
include: {
user: {
where: { userId: req.user.sub },
},
},
include: branchRelationPermInclude(req.user),
where: { id: branchId },
});
if (
!globalAllow(req.user) &&
branch?.createdByUserId !== req.user.sub &&
!branch?.user.find((v) => v.userId === req.user.sub)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
await permissionCheck(req.user, branch);
await prisma.$transaction(
body.user.map((v) => prisma.branchUser.deleteMany({ where: { branchId, userId: v } })),

View file

@ -19,6 +19,7 @@ import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import minio from "../services/minio";
import { isSystem } from "../utils/keycloak";
import { branchRelationPermInclude, createPermCheck } from "../services/permission";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
@ -40,6 +41,8 @@ function globalAllow(user: RequestWithUser["user"]) {
return allowList.some((v) => user.roles?.includes(v));
}
const permissionCheck = createPermCheck(globalAllow);
function imageLocation(id: string) {
return `employee/profile-img-${id}`;
}
@ -325,18 +328,7 @@ export class CustomerBranchController extends Controller {
where: { id: body.customerId || undefined },
include: {
registeredBranch: {
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
},
branch: {
take: 1,
@ -370,29 +362,7 @@ export class CustomerBranchController extends Controller {
"relationCustomerNotFound",
);
if (!isSystem(req.user)) {
const _branch = 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",
);
}
}
}
await permissionCheck(req.user, customer.registeredBranch);
const { provinceId, districtId, subDistrictId, customerId, ...rest } = body;
@ -472,18 +442,7 @@ export class CustomerBranchController extends Controller {
customer: {
include: {
registeredBranch: {
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
},
},
},
@ -494,29 +453,7 @@ export class CustomerBranchController extends Controller {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
}
if (!isSystem(req.user)) {
const _branch = branch.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",
);
}
}
}
await permissionCheck(req.user, branch.customer.registeredBranch);
if (!body.customerId) body.customerId = branch.customerId;
@ -529,18 +466,7 @@ export class CustomerBranchController extends Controller {
where: { id: body.customerId || undefined },
include: {
registeredBranch: {
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
},
},
}),
@ -569,29 +495,7 @@ export class CustomerBranchController extends Controller {
"Customer cannot be found.",
"relationCustomerNotFound",
);
if (!isSystem(req.user)) {
const _branch = 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",
);
}
}
}
await permissionCheck(req.user, customer.registeredBranch);
}
const { provinceId, districtId, subDistrictId, customerId, ...rest } = body;
@ -635,18 +539,7 @@ export class CustomerBranchController extends Controller {
customer: {
include: {
registeredBranch: {
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
},
},
},
@ -661,30 +554,7 @@ export class CustomerBranchController extends Controller {
);
}
if (!isSystem(req.user)) {
const _branch = record.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",
);
}
}
}
await permissionCheck(req.user, record.customer.registeredBranch);
if (record.status !== Status.CREATED) {
throw new HttpError(

View file

@ -19,6 +19,7 @@ import minio, { deleteFolder, presignedGetObjectIfExist } from "../services/mini
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { isSystem } from "../utils/keycloak";
import { branchRelationPermInclude, createPermCheck } from "../services/permission";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
@ -40,6 +41,8 @@ function globalAllow(user: RequestWithUser["user"]) {
return allowList.some((v) => user.roles?.includes(v));
}
const permissionCheck = createPermCheck(globalAllow);
export type CustomerCreate = {
registeredBranchId?: string;
@ -243,18 +246,7 @@ export class CustomerController extends Controller {
const [branch] = await prisma.$transaction([
prisma.branch.findFirst({
where: { id: body.registeredBranchId },
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
}),
]);
@ -266,30 +258,8 @@ export class CustomerController extends Controller {
);
}
if (body.registeredBranchId !== undefined && !isSystem(req.user)) {
if (!globalAllow(req.user)) {
if (body.registeredBranchId === null || (branch && branch.user.length === 0)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
} else {
if (
body.registeredBranchId === null ||
(branch &&
branch.user.length === 0 &&
branch.headOffice &&
branch.headOffice.user.length === 0)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
}
if (body.registeredBranchId !== undefined && branch) {
await permissionCheck(req.user, branch);
}
const record = await prisma.$transaction(
@ -343,7 +313,14 @@ export class CustomerController extends Controller {
body.registeredBranchId = undefined;
}
const customer = await prisma.customer.findUnique({ where: { id: customerId } });
const customer = await prisma.customer.findUnique({
where: { id: customerId },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
});
if (!customer) {
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
@ -352,18 +329,7 @@ export class CustomerController extends Controller {
const [branch] = await prisma.$transaction([
prisma.branch.findFirst({
where: { id: body.registeredBranchId },
include: {
user: {
where: { userId: req.user.sub },
},
headOffice: {
include: {
user: {
where: { userId: req.user.sub },
},
},
},
},
include: branchRelationPermInclude(req.user),
}),
]);
@ -375,30 +341,10 @@ export class CustomerController extends Controller {
);
}
if (body.registeredBranchId !== undefined && !isSystem(req.user)) {
if (!globalAllow(req.user)) {
if (body.registeredBranchId === null || (branch && branch.user.length === 0)) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
} else {
if (
body.registeredBranchId === null ||
(branch &&
branch.user.length === 0 &&
branch.headOffice &&
branch.headOffice.user.length === 0)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
}
await permissionCheck(req.user, customer.registeredBranch);
if (body.registeredBranchId !== undefined && branch) {
await permissionCheck(req.user, branch);
}
const record = await prisma.$transaction(async (tx) => {
@ -433,15 +379,7 @@ export class CustomerController extends Controller {
where: { id: customerId },
include: {
registeredBranch: {
include: {
headOffice: {
include: {
branch: { where: { user: { some: { userId: req.user.sub } } } },
user: { where: { userId: req.user.sub } },
},
},
user: { where: { userId: req.user.sub } },
},
include: branchRelationPermInclude(req.user),
},
},
});
@ -450,28 +388,7 @@ export class CustomerController extends Controller {
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
}
if (!isSystem(req.user)) {
if (!globalAllow(req.user) && record.registeredBranch?.user.length === 0) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
} else {
if (
(record.registeredBranch?.user.length === 0 && !record.registeredBranch?.headOffice) ||
(record.registeredBranch?.headOffice &&
record.registeredBranch?.headOffice.user.length === 0 &&
record.registeredBranch?.headOffice.branch.length === 0)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
}
}
await permissionCheck(req.user, record.registeredBranch);
if (record.status !== Status.CREATED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Customer is in used.", "customerInUsed");
@ -500,12 +417,19 @@ export class CustomerController extends Controller {
async setCustomerImageById(@Request() req: RequestWithUser, @Path() customerId: string) {
const record = await prisma.customer.findFirst({
where: { id: customerId },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
});
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
}
await permissionCheck(req.user, record.registeredBranch);
return req.res?.redirect(
await minio.presignedPutObject(MINIO_BUCKET, imageLocation(customerId), 12 * 60 * 60),
);

View 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;
};
}