feat: permmission branch

This commit is contained in:
Methapon2001 2024-07-02 13:46:22 +07:00
parent c464da6228
commit 9618c261e3

View file

@ -80,9 +80,9 @@ function branchImageLoc(id: string) {
@Route("api/v1/branch") @Route("api/v1/branch")
@Tags("Branch") @Tags("Branch")
@Security("keycloak")
export class BranchController extends Controller { export class BranchController extends Controller {
@Get("stats") @Get("stats")
@Security("keycloak")
async getStats() { async getStats() {
const list = await prisma.branch.groupBy({ const list = await prisma.branch.groupBy({
_count: true, _count: true,
@ -99,14 +99,27 @@ export class BranchController extends Controller {
} }
@Get("user-stats") @Get("user-stats")
async getUserStat(@Query() userType?: UserType) { @Security("keycloak")
async getUserStat(@Request() req: RequestWithUser, @Query() userType?: UserType) {
const list = await prisma.branchUser.groupBy({ const list = await prisma.branchUser.groupBy({
_count: true, _count: true,
where: { user: { userType } }, where: {
userId: !["system", "head_of_admin", "admin"].some((v) => req.user.role?.includes(v))
? req.user.sub
: undefined,
user: {
userType,
},
},
by: "branchId", by: "branchId",
}); });
const record = await prisma.branch.findMany({ const record = await prisma.branch.findMany({
where: {
user: !["system", "head_of_admin", "admin"].some((v) => req.user.role?.includes(v))
? { some: { userId: req.user.sub } }
: undefined,
},
select: { select: {
id: true, id: true,
headOfficeId: true, headOfficeId: true,
@ -136,7 +149,9 @@ export class BranchController extends Controller {
} }
@Get() @Get()
@Security("keycloak")
async getBranch( async getBranch(
@Request() req: RequestWithUser,
@Query() zipCode?: string, @Query() zipCode?: string,
@Query() filter?: "head" | "sub", @Query() filter?: "head" | "sub",
@Query() headOfficeId?: string, @Query() headOfficeId?: string,
@ -147,6 +162,9 @@ export class BranchController extends Controller {
) { ) {
const where = { const where = {
AND: { AND: {
user: !["system", "head_of_admin", "admin"].some((v) => req.user.role?.includes(v))
? { some: { userId: req.user.sub } }
: undefined,
headOfficeId: headOfficeId ?? (filter === "head" || tree ? null : undefined), headOfficeId: headOfficeId ?? (filter === "head" || tree ? null : undefined),
NOT: { headOfficeId: filter === "sub" && !headOfficeId ? null : undefined }, NOT: { headOfficeId: filter === "sub" && !headOfficeId ? null : undefined },
}, },
@ -187,6 +205,7 @@ export class BranchController extends Controller {
} }
@Get("{branchId}") @Get("{branchId}")
@Security("keycloak")
async getBranchById( async getBranchById(
@Path() branchId: string, @Path() branchId: string,
@Query() includeSubBranch?: boolean, @Query() includeSubBranch?: boolean,
@ -222,6 +241,7 @@ export class BranchController extends Controller {
} }
@Post() @Post()
@Security("keycloak", ["system", "head_of_admin", "admin"])
async createBranch(@Request() req: RequestWithUser, @Body() body: BranchCreate) { async createBranch(@Request() req: RequestWithUser, @Body() body: BranchCreate) {
const [province, district, subDistrict, head] = await prisma.$transaction([ const [province, district, subDistrict, head] = await prisma.$transaction([
prisma.province.findFirst({ where: { id: body.provinceId || undefined } }), prisma.province.findFirst({ where: { id: body.provinceId || undefined } }),
@ -336,6 +356,7 @@ export class BranchController extends Controller {
} }
@Put("{branchId}") @Put("{branchId}")
@Security("keycloak", ["system", "head_of_admin", "admin", "branch_admin", "branch_manager"])
async editBranch( async editBranch(
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Body() body: BranchUpdate, @Body() body: BranchUpdate,
@ -383,10 +404,30 @@ export class BranchController extends Controller {
const { provinceId, districtId, subDistrictId, headOfficeId, contact, ...rest } = body; const { provinceId, districtId, subDistrictId, headOfficeId, contact, ...rest } = body;
if (!(await prisma.branch.findUnique({ where: { id: branchId } }))) { const branch = await prisma.branch.findUnique({
include: {
user: { where: { id: req.user.sub } },
},
where: { id: branchId },
});
if (!branch) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
} }
if (!["system", "head_of_admin", "admin"].some((v) => req.user.role?.includes(v))) {
if (
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",
);
}
}
const record = await prisma.branch.update({ const record = await prisma.branch.update({
include: { province: true, district: true, subDistrict: true }, include: { province: true, district: true, subDistrict: true },
data: { data: {
@ -442,7 +483,8 @@ export class BranchController extends Controller {
} }
@Delete("{branchId}") @Delete("{branchId}")
async deleteBranch(@Path() branchId: string) { @Security("keycloak", ["system", "head_of_admin", "admin", "branch_manager"])
async deleteBranch(@Request() req: RequestWithUser, @Path() branchId: string) {
const record = await prisma.branch.findFirst({ const record = await prisma.branch.findFirst({
include: { include: {
province: true, province: true,
@ -450,10 +492,24 @@ export class BranchController extends Controller {
subDistrict: true, subDistrict: true,
createdBy: true, createdBy: true,
updatedBy: true, updatedBy: true,
user: { where: { id: req.user.sub } },
}, },
where: { id: branchId }, where: { id: branchId },
}); });
if (!["system", "head_of_admin", "admin"].some((v) => req.user.role?.includes(v))) {
if (
record?.createdByUserId !== req.user.sub &&
!record?.user.find((v) => v.userId === req.user.sub)
) {
throw new HttpError(
HttpStatus.FORBIDDEN,
"You do not have permission to perform this action.",
"noPermission",
);
}
}
if (!record) { if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound"); throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.", "branchNotFound");
} }