feat: permission control

This commit is contained in:
Methapon Metanipat 2024-09-05 09:01:34 +07:00
parent 42cce880cd
commit b53dcb3a19

View file

@ -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",
);
}
}
}