refactor: view condition and permission

This commit is contained in:
Methapon Metanipat 2024-09-04 13:48:59 +07:00
parent 9f426d9b08
commit e61111cac7
3 changed files with 118 additions and 117 deletions

View file

@ -27,6 +27,10 @@ if (!process.env.MINIO_BUCKET) {
const MINIO_BUCKET = process.env.MINIO_BUCKET; const MINIO_BUCKET = process.env.MINIO_BUCKET;
const MANAGE_ROLES = ["system", "head_of_admin"]; const MANAGE_ROLES = ["system", "head_of_admin"];
function globalAllow(user: RequestWithUser["user"]) {
return MANAGE_ROLES.some((v) => user.roles?.includes(v));
}
type BranchCreate = { type BranchCreate = {
status?: Status; status?: Status;
code: string; code: string;
@ -191,10 +195,17 @@ export class BranchController extends Controller {
AND: { AND: {
zipCode, zipCode,
headOfficeId: headOfficeId ?? (filter === "head" || tree ? null : undefined), headOfficeId: headOfficeId ?? (filter === "head" || tree ? null : undefined),
user: !MANAGE_ROLES.some((v) => req.user.roles?.includes(v))
? { some: { userId: req.user.sub } }
: undefined,
NOT: { headOfficeId: filter === "sub" && !headOfficeId ? null : undefined }, NOT: { headOfficeId: filter === "sub" && !headOfficeId ? null : undefined },
OR: globalAllow(req.user)
? undefined
: [
{ user: !globalAllow(req.user) ? { some: { userId: req.user.sub } } : undefined },
{
headOffice: !globalAllow(req.user)
? { user: { some: { userId: req.user.sub } } }
: undefined,
},
],
}, },
OR: [ OR: [
{ nameEN: { contains: query } }, { nameEN: { contains: query } },

View file

@ -18,6 +18,13 @@ import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status"; import HttpStatus from "../interfaces/http-status";
import { RequestWithUser } from "../interfaces/user"; import { RequestWithUser } from "../interfaces/user";
const MANAGE_ROLES = ["system", "head_of_admin", "admin", "branch_manager"];
function globalAllow(user: RequestWithUser["user"]) {
const listAllowed = ["system", "head_of_admin", "admin"];
return user.roles?.some((v) => listAllowed.includes(v)) || false;
}
type BranchUserBody = { user: string[] }; type BranchUserBody = { user: string[] };
async function userBranchCodeGen(branch: Branch, user: User[]) { async function userBranchCodeGen(branch: Branch, user: User[]) {
@ -60,7 +67,7 @@ async function userBranchCodeGen(branch: Branch, user: User[]) {
@Route("api/v1/branch/{branchId}/manager") @Route("api/v1/branch/{branchId}/manager")
@Tags("Branch User") @Tags("Branch User")
export class BranchAdminUserController extends Controller { export class BranchManagerUserController extends Controller {
@Get() @Get()
@Security("keycloak") @Security("keycloak")
async getBranchAdmin(@Path() branchId: string) { async getBranchAdmin(@Path() branchId: string) {
@ -75,6 +82,55 @@ export class BranchAdminUserController extends Controller {
} }
} }
@Route("api/v1/user/{userId}/branch")
@Tags("Branch User")
export class UserBranchController extends Controller {
@Get()
@Security("keycloak")
async getUserBranch(
@Path() userId: string,
@Query() zipCode?: string,
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
OR: [
{ branch: { name: { contains: query }, zipCode }, userId },
{ branch: { nameEN: { contains: query }, zipCode }, userId },
],
} satisfies Prisma.BranchUserWhereInput;
const [result, total] = await prisma.$transaction([
prisma.branchUser.findMany({
orderBy: { branch: { createdAt: "asc" } },
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
headOffice: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
},
},
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.branchUser.count({ where }),
]);
return { result: result.map((v) => v.branch), page, pageSize, total };
}
}
@Route("api/v1/branch/{branchId}/user") @Route("api/v1/branch/{branchId}/user")
@Tags("Branch User") @Tags("Branch User")
export class BranchUserController extends Controller { export class BranchUserController extends Controller {
@ -121,7 +177,7 @@ export class BranchUserController extends Controller {
} }
@Post() @Post()
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_admin", "branch_manager"]) @Security("keycloak", MANAGE_ROLES)
async createBranchUser( async createBranchUser(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Path() branchId: string, @Path() branchId: string,
@ -143,7 +199,7 @@ export class BranchUserController extends Controller {
]); ]);
if ( if (
!["system", "head_of_admin", "admin"].some((v) => req.user.roles?.includes(v)) && !globalAllow(req.user) &&
branch?.createdByUserId !== req.user.sub && branch?.createdByUserId !== req.user.sub &&
!branch?.user.find((v) => v.userId === req.user.sub) !branch?.user.find((v) => v.userId === req.user.sub)
) { ) {
@ -187,10 +243,37 @@ export class BranchUserController extends Controller {
} }
@Delete() @Delete()
async deleteBranchUser(@Path() branchId: string, @Body() body: BranchUserBody) { @Security("keycloak", MANAGE_ROLES)
async deleteBranchUser(
@Request() req: RequestWithUser,
@Path() branchId: string,
@Body() body: BranchUserBody,
) {
const branch = await prisma.branch.findUnique({
include: {
user: {
where: { userId: req.user.sub },
},
},
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 prisma.$transaction( await prisma.$transaction(
body.user.map((v) => prisma.branchUser.deleteMany({ where: { branchId, userId: v } })), body.user.map((v) => prisma.branchUser.deleteMany({ where: { branchId, userId: v } })),
); );
await prisma.user.updateMany({ await prisma.user.updateMany({
where: { where: {
branch: { none: {} }, branch: { none: {} },
@ -200,123 +283,31 @@ export class BranchUserController extends Controller {
} }
@Delete("{userId}") @Delete("{userId}")
async deleteBranchUserById(@Path() branchId: string, @Path() userId: string) { async deleteBranchUserById(
await prisma.branchUser.deleteMany({
where: { branchId, userId },
});
await prisma.user.updateMany({
where: {
id: userId,
branch: { none: {} },
},
data: { code: null },
});
}
}
type UserBranchBody = { branch: string[] };
@Route("api/v1/user/{userId}/branch")
@Tags("Branch User")
@Security("keycloak")
export class UserBranchController extends Controller {
@Get()
async getUserBranch(
@Path() userId: string,
@Query() zipCode?: string,
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
OR: [
{ branch: { name: { contains: query }, zipCode }, userId },
{ branch: { nameEN: { contains: query }, zipCode }, userId },
],
} satisfies Prisma.BranchUserWhereInput;
const [result, total] = await prisma.$transaction([
prisma.branchUser.findMany({
orderBy: { branch: { createdAt: "asc" } },
include: {
branch: {
include: {
province: true,
district: true,
subDistrict: true,
headOffice: {
include: {
province: true,
district: true,
subDistrict: true,
},
},
},
},
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.branchUser.count({ where }),
]);
return { result: result.map((v) => v.branch), page, pageSize, total };
}
@Post()
async createUserBranch(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Path() branchId: string,
@Path() userId: string, @Path() userId: string,
@Body() body: UserBranchBody,
) { ) {
const branch = await prisma.branch.findMany({ const branch = await prisma.branch.findUnique({
include: { user: true }, include: {
where: { id: { in: body.branch } }, user: {
where: { userId: req.user.sub },
},
},
where: { id: branchId },
}); });
if (branch.length !== body.branch.length) { if (
!globalAllow(req.user) &&
branch?.createdByUserId !== req.user.sub &&
!branch?.user.find((v) => v.userId === req.user.sub)
) {
throw new HttpError( throw new HttpError(
HttpStatus.BAD_REQUEST, HttpStatus.FORBIDDEN,
"One or more branch cannot be found.", "You do not have permission to perform this action.",
"oneOrMoreBranchBadReq", "noPermission",
); );
} }
await prisma.branch.updateMany({
where: { id: { in: body.branch }, status: Status.CREATED },
data: { status: Status.ACTIVE },
});
await prisma.branchUser.createMany({
data: branch
.filter((a) => !a.user.some((b) => b.userId === userId))
.map((v) => ({
branchId: v.id,
userId,
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
})),
});
this.setStatus(HttpStatus.CREATED);
}
@Delete()
async deleteUserBranch(@Path() userId: string, @Body() body: UserBranchBody) {
await prisma.$transaction(
body.branch.map((v) => prisma.branchUser.deleteMany({ where: { userId, branchId: v } })),
);
await prisma.user.updateMany({
where: {
branch: { none: {} },
},
data: { code: null },
});
}
@Delete("{branchId}")
async deleteUserBranchById(@Path() branchId: string, @Path() userId: string) {
await prisma.branchUser.deleteMany({ await prisma.branchUser.deleteMany({
where: { branchId, userId }, where: { branchId, userId },
}); });

View file

@ -20,7 +20,6 @@
{ "name": "Permission" }, { "name": "Permission" },
{ "name": "Address" }, { "name": "Address" },
{ "name": "Branch" }, { "name": "Branch" },
{ "name": "Branch Contact" },
{ "name": "User" }, { "name": "User" },
{ "name": "Branch User" }, { "name": "Branch User" },
{ "name": "Customer" }, { "name": "Customer" },