diff --git a/src/controllers/customer-controller.ts b/src/controllers/customer-controller.ts index da1008d..13187fd 100644 --- a/src/controllers/customer-controller.ts +++ b/src/controllers/customer-controller.ts @@ -18,6 +18,7 @@ import prisma from "../db"; import minio, { deleteFolder, presignedGetObjectIfExist } from "../services/minio"; import HttpStatus from "../interfaces/http-status"; import HttpError from "../interfaces/http-error"; +import { isSystem } from "../utils/keycloak"; if (!process.env.MINIO_BUCKET) { throw Error("Require MinIO bucket."); @@ -200,6 +201,13 @@ export class CustomerController extends Controller { user: { where: { userId: req.user.sub }, }, + headOffice: { + include: { + user: { + where: { userId: req.user.sub }, + }, + }, + }, }, }), ]); @@ -212,13 +220,29 @@ export class CustomerController extends Controller { ); } - if (body.registeredBranchId !== undefined && !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", - ); + 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", + ); + } } } @@ -286,6 +310,13 @@ export class CustomerController extends Controller { user: { where: { userId: req.user.sub }, }, + headOffice: { + include: { + user: { + where: { userId: req.user.sub }, + }, + }, + }, }, }), ]); @@ -298,13 +329,29 @@ export class CustomerController extends Controller { ); } - if (body.registeredBranchId !== undefined && !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", - ); + 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", + ); + } } }