From 57f56671b57122f3cf6325da730c396b064b84a5 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Wed, 17 Apr 2024 16:22:07 +0700 Subject: [PATCH] feat: add field --- src/controllers/user-controller.ts | 32 ++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/controllers/user-controller.ts b/src/controllers/user-controller.ts index 52b275a..9640367 100644 --- a/src/controllers/user-controller.ts +++ b/src/controllers/user-controller.ts @@ -19,7 +19,7 @@ import minio from "../services/minio"; import { RequestWithUser } from "../interfaces/user"; import HttpError from "../interfaces/http-error"; import HttpStatus from "../interfaces/http-status"; -import { createUser, deleteUser } from "../services/keycloak"; +import { addUserRoles, createUser, deleteUser, getRoles } from "../services/keycloak"; if (!process.env.MINIO_BUCKET) { throw Error("Require MinIO bucket."); @@ -41,6 +41,8 @@ type UserCreate = { lastNameEN: string; gender: string; + checkpoint?: string | null; + checkpointEN?: string | null; registrationNo?: string | null; startDate?: Date | null; retireDate?: Date | null; @@ -77,6 +79,8 @@ type UserUpdate = { lastNameEN?: string; gender?: string; + checkpoint?: string | null; + checkpointEN?: string | null; registrationNo?: string | null; startDate?: Date | null; retireDate?: Date | null; @@ -240,21 +244,41 @@ export class UserController extends Controller { const { provinceId, districtId, subDistrictId, username, ...rest } = body; - const result = await createUser(username, username, { + 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 userId = await createUser(username, username, { firstName: body.firstName, lastName: body.lastName, requiredActions: ["UPDATE_PASSWORD"], }); - if (!result || typeof result !== "string") { + if (!userId || typeof userId !== "string") { throw new Error("Cannot create user with keycloak service."); } + const role = list.find((v) => v.id === body.userRole); + + const resultAddRole = role && (await addUserRoles(userId, [role])); + + if (!resultAddRole) { + await deleteUser(userId); + throw new Error("Failed. Cannot set user's role."); + } + const record = await prisma.user.create({ include: { province: true, district: true, subDistrict: true }, data: { - id: result, + id: userId, ...rest, + userRole: role.name, province: { connect: provinceId ? { id: provinceId } : undefined }, district: { connect: districtId ? { id: districtId } : undefined }, subDistrict: { connect: subDistrictId ? { id: subDistrictId } : undefined },