From f91c9c2f145027f0ef73a05d73380c7d1afb1d4d Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Wed, 17 Apr 2024 16:35:35 +0700 Subject: [PATCH] feat: edit user role --- src/controllers/user-controller.ts | 31 +++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/controllers/user-controller.ts b/src/controllers/user-controller.ts index 9640367..2af6d33 100644 --- a/src/controllers/user-controller.ts +++ b/src/controllers/user-controller.ts @@ -19,7 +19,14 @@ import minio from "../services/minio"; import { RequestWithUser } from "../interfaces/user"; import HttpError from "../interfaces/http-error"; import HttpStatus from "../interfaces/http-status"; -import { addUserRoles, createUser, deleteUser, getRoles } from "../services/keycloak"; +import { + addUserRoles, + createUser, + deleteUser, + getRoles, + getUserRoles, + removeUserRoles, +} from "../services/keycloak"; if (!process.env.MINIO_BUCKET) { throw Error("Require MinIO bucket."); @@ -336,6 +343,27 @@ export class UserController extends Controller { ); } + let list = await getRoles(); + + if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); + if (Array.isArray(list)) { + list = list.filter( + (a) => + !["uma_authorization", "offline_access", "default-roles"].some((b) => a.name.includes(b)), + ); + } + const currentRole = await getUserRoles(userId); + + const role = list.find((v) => v.id === body.userRole); + + const resultAddRole = role && (await addUserRoles(userId, [role])); + + if (!resultAddRole) { + throw new Error("Failed. Cannot set user's role."); + } else { + if (Array.isArray(currentRole)) await removeUserRoles(userId, currentRole); + } + const { provinceId, districtId, subDistrictId, ...rest } = body; const user = await prisma.user.findFirst({ @@ -362,6 +390,7 @@ export class UserController extends Controller { include: { province: true, district: true, subDistrict: true }, data: { ...rest, + userRole: role.name, code: (lastUserOfType && `${user.code?.slice(0, 3)}${body.userType !== "USER" ? body.userType?.charAt(0) : ""}${(+(lastUserOfType?.code?.slice(-4) || 0) + 1).toString().padStart(4, "0")}`) ||