feat: edit user role

This commit is contained in:
Methapon2001 2024-04-17 16:35:35 +07:00
parent 4592192327
commit f91c9c2f14

View file

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