refactor: use factory function for perm check
This commit is contained in:
parent
9e745ee81c
commit
cbdb4c0e7a
5 changed files with 131 additions and 320 deletions
|
|
@ -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")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue