From cbdb4c0e7a41476659a443915ce1014c27fcf52f Mon Sep 17 00:00:00 2001 From: Methapon Metanipat Date: Mon, 9 Sep 2024 14:40:18 +0700 Subject: [PATCH] refactor: use factory function for perm check --- src/controllers/01-branch-controller.ts | 44 +---- src/controllers/01-branch-user-controller.ts | 52 +++--- .../03-customer-branch-controller.ts | 152 ++---------------- src/controllers/03-customer-controller.ts | 132 ++++----------- src/services/permission.ts | 71 ++++++++ 5 files changed, 131 insertions(+), 320 deletions(-) create mode 100644 src/services/permission.ts diff --git a/src/controllers/01-branch-controller.ts b/src/controllers/01-branch-controller.ts index d32973d..939749b 100644 --- a/src/controllers/01-branch-controller.ts +++ b/src/controllers/01-branch-controller.ts @@ -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") diff --git a/src/controllers/01-branch-user-controller.ts b/src/controllers/01-branch-user-controller.ts index cf5167e..645634e 100644 --- a/src/controllers/01-branch-user-controller.ts +++ b/src/controllers/01-branch-user-controller.ts @@ -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 } })), diff --git a/src/controllers/03-customer-branch-controller.ts b/src/controllers/03-customer-branch-controller.ts index 9b3bff3..c3b70e9 100644 --- a/src/controllers/03-customer-branch-controller.ts +++ b/src/controllers/03-customer-branch-controller.ts @@ -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( diff --git a/src/controllers/03-customer-controller.ts b/src/controllers/03-customer-controller.ts index 6b764da..6f7a536 100644 --- a/src/controllers/03-customer-controller.ts +++ b/src/controllers/03-customer-controller.ts @@ -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), ); diff --git a/src/services/permission.ts b/src/services/permission.ts new file mode 100644 index 0000000..89a289e --- /dev/null +++ b/src/services/permission.ts @@ -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> | 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; + }; +}