This commit is contained in:
Bright 2025-01-22 17:42:23 +07:00
parent dcc53befb2
commit 9f5f1af6e2
3 changed files with 123 additions and 82 deletions

View file

@ -53,7 +53,7 @@ import { PosMasterAct } from "../entities/PosMasterAct";
import { sendToQueue } from "../services/rabbitmq"; import { sendToQueue } from "../services/rabbitmq";
import { PosLevel } from "../entities/PosLevel"; import { PosLevel } from "../entities/PosLevel";
import { PosType } from "../entities/PosType"; import { PosType } from "../entities/PosType";
import { addUserRoles, createUser, getRoles, deleteUser, enableStatus } from "../keycloak"; import { addUserRoles, createUser, getRoles, deleteUser, enableStatus, getUserByUsername, getRoleMappings } from "../keycloak";
import { ProfileEducation, CreateProfileEducation } from "../entities/ProfileEducation"; import { ProfileEducation, CreateProfileEducation } from "../entities/ProfileEducation";
import { ProfileEducationHistory } from "../entities/ProfileEducationHistory"; import { ProfileEducationHistory } from "../entities/ProfileEducationHistory";
import { CreateProfileCertificate, ProfileCertificate } from "../entities/ProfileCertificate"; import { CreateProfileCertificate, ProfileCertificate } from "../entities/ProfileCertificate";
@ -2564,47 +2564,37 @@ export class CommandController extends Controller {
//คำสั่งบรรจุกลับเข้ารับราชการ หรือ ผู้ออกไปรับราชการทหารกลับเข้ารับราชการ solutionเดิม ให้ enable user เปลี่ยนเป็นสร้าง user ใหม่เลยเพราะยังไงตอนถูกพักก็ถูกลบ user //คำสั่งบรรจุกลับเข้ารับราชการ หรือ ผู้ออกไปรับราชการทหารกลับเข้ารับราชการ solutionเดิม ให้ enable user เปลี่ยนเป็นสร้าง user ใหม่เลยเพราะยังไงตอนถูกพักก็ถูกลบ user
if (returnWork && item.isGovernment) { if (returnWork && item.isGovernment) {
let userKeycloakId; let userKeycloakId;
userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { const checkUser = await getUserByUsername(profile.citizenId)
firstName: profile.firstName, //ถ้ายังไม่มี user keycloak ให้สร้างใหม่
lastName: profile.lastName, if (checkUser.length == 0) {
}); userKeycloakId = await createUser(profile.citizenId, profile.citizenId, {
// กรณี Keycloak ไม่ถูกลบ ให้ลบซ้ำอีกรอบแล้วสร้างใหม่ และหากยังไม่สามารถลบได้ให้แสดง Error firstName: profile.firstName,
if ( lastName: profile.lastName,
profile.keycloak != null && });
userKeycloakId && const list = await getRoles();
userKeycloakId.errorMessage === "User exists with same username" let result = false;
) { if (Array.isArray(list) && userKeycloakId) {
const delUserKeycloak = await deleteUser(profile.keycloak); result = await addUserRoles(
if (delUserKeycloak) { userKeycloakId,
userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { list
firstName: profile.firstName, .filter((v) => v.name === "USER")
lastName: profile.lastName, .map((x) => ({
}); id: x.id,
} else { name: x.name,
throw new HttpError( })),
HttpStatus.BAD_REQUEST,
"พบข้อผิดพลาด ไม่สามารถจัดการผู้ใช้งานได้",
); );
} }
profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : [];
profile.keycloak = userKeycloakId && typeof userKeycloakId === "string" ? userKeycloakId : "";;
} }
const list = await getRoles(); //ถ้ามีอยู่แล้วให้ใช้อันเดิม
let result = false; else {
if (Array.isArray(list) && userKeycloakId) { // const _roleKeycloaks = await getRoleMappings(checkUser[0].id);
result = await addUserRoles( profile.keycloak = checkUser[0].id;
userKeycloakId,
list
.filter((v) => v.name === "USER")
.map((x) => ({
id: x.id,
name: x.name,
})),
);
} }
profile.amount = item.amount ?? _null; profile.amount = item.amount ?? _null;
profile.amountSpecial = item.amountSpecial ?? _null; profile.amountSpecial = item.amountSpecial ?? _null;
profile.isActive = true; profile.isActive = true;
profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : "";
profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : [];
} }
await this.profileRepository.save(profile); await this.profileRepository.save(profile);
}), }),
@ -3929,26 +3919,32 @@ export class CommandController extends Controller {
item.bodyProfile.birthDate == null item.bodyProfile.birthDate == null
? _null ? _null
: calculateRetireLaw(item.bodyProfile.birthDate); : calculateRetireLaw(item.bodyProfile.birthDate);
const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, {
firstName: profile.firstName, const checkUser = await getUserByUsername(profile.citizenId)
lastName: profile.lastName, if(checkUser.length == 0) {
}); const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, {
// if (typeof userKeycloakId !== "string") { firstName: profile.firstName,
// throw new Error(userKeycloakId.errorMessage); lastName: profile.lastName,
// } });
const list = await getRoles(); const list = await getRoles();
if (!Array.isArray(list)) if (!Array.isArray(list))
throw new Error("Failed. Cannot get role(s) data from the server."); throw new Error("Failed. Cannot get role(s) data from the server.");
const result = await addUserRoles( const result = await addUserRoles(
userKeycloakId, userKeycloakId,
list list
.filter((v) => v.name === "USER") .filter((v) => v.name === "USER")
.map((x) => ({ .map((x) => ({
id: x.id, id: x.id,
name: x.name, name: x.name,
})), })),
); );
// if (!result) throw new Error("Failed. Cannot set user's role."); profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : [];
profile.keycloak = userKeycloakId && typeof userKeycloakId === "string" ? userKeycloakId : "";
}
else {
profile.keycloak = checkUser[0].id;
}
let registrationProvinceId = await this.provinceRepo.findOneBy({ let registrationProvinceId = await this.provinceRepo.findOneBy({
id: profile.registrationProvinceId, id: profile.registrationProvinceId,
}); });
@ -3980,8 +3976,6 @@ export class CommandController extends Controller {
id: profile.currentSubDistrictId, id: profile.currentSubDistrictId,
}); });
profile.currentSubDistrictId = currentSubDistrictId ? currentSubDistrictId.id : null_; profile.currentSubDistrictId = currentSubDistrictId ? currentSubDistrictId.id : null_;
profile.keycloak = typeof userKeycloakId === "string" ? userKeycloakId : "";
profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : [];
profile.email = item.bodyProfile.email; profile.email = item.bodyProfile.email;
profile.dateStart = item.bodyProfile.dateStart; profile.dateStart = item.bodyProfile.dateStart;
profile.amount = item.bodyProfile.amount ?? null; profile.amount = item.bodyProfile.amount ?? null;
@ -4317,30 +4311,36 @@ export class CommandController extends Controller {
if (positionNew != null) { if (positionNew != null) {
// Create Keycloak // Create Keycloak
const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, { const checkUser = await getUserByUsername(profile.citizenId)
firstName: profile.firstName, if(checkUser.length == 0) {
lastName: profile.lastName, const userKeycloakId = await createUser(profile.citizenId, profile.citizenId, {
// email: profile.email, firstName: profile.firstName,
}); lastName: profile.lastName,
// if (typeof userKeycloakId !== "string") { // email: profile.email,
// throw new Error(userKeycloakId.errorMessage); });
// } // if (typeof userKeycloakId !== "string") {
const list = await getRoles(); // throw new Error(userKeycloakId.errorMessage);
if (!Array.isArray(list)) // }
throw new Error("Failed. Cannot get role(s) data from the server."); const list = await getRoles();
const result = await addUserRoles( if (!Array.isArray(list))
userKeycloakId, throw new Error("Failed. Cannot get role(s) data from the server.");
list const result = await addUserRoles(
.filter((v) => v.name === "USER") userKeycloakId,
.map((x) => ({ list
id: x.id, .filter((v) => v.name === "USER")
name: x.name, .map((x) => ({
})), id: x.id,
); name: x.name,
// if (!result) throw new Error("Failed. Cannot set user's role."); })),
profile.keycloak = typeof userKeycloakId == "string" ? userKeycloakId : ""; );
profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : []; // if (!result) throw new Error("Failed. Cannot set user's role.");
// End Create Keycloak profile.keycloak = userKeycloakId && typeof userKeycloakId == "string" ? userKeycloakId : "";
profile.roleKeycloaks = result && roleKeycloak ? [roleKeycloak] : [];
// End Create Keycloak
}
else {
profile.keycloak = checkUser[0].id;
}
positionNew.positionIsSelected = true; positionNew.positionIsSelected = true;
profile.posLevelId = positionNew.posLevelId; profile.posLevelId = positionNew.posLevelId;

View file

@ -30,6 +30,7 @@ import {
getRoleMappings, getRoleMappings,
getUserCount, getUserCount,
enableStatus, enableStatus,
getUserByUsername
} from "../keycloak"; } from "../keycloak";
import { AppDataSource } from "../database/data-source"; import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile"; import { Profile } from "../entities/Profile";
@ -693,6 +694,24 @@ export class KeycloakController extends Controller {
return profile.roleKeycloaks; return profile.roleKeycloaks;
} }
@Get("user/username/{citizenId}")
async getUserByUsername(@Path("citizenId") citizenId: string) {
const userData = await getUserByUsername(citizenId);
if (!userData || userData.length == 0) {
throw new Error("User not found");
}
const rolesData = await getRoleMappings(userData[0].id);
if (!rolesData) {
throw new Error("Role mappings not found");
}
const userDataWithRoles = {
...userData,
roles: rolesData,
};
return userDataWithRoles
}
@Put("user/{userId}/enableStatus/{status}") //#log? @Put("user/{userId}/enableStatus/{status}") //#log?
async changeEnableStatus(@Path() userId: string, @Path() status: boolean) { async changeEnableStatus(@Path() userId: string, @Path() status: boolean) {
const profile = await this.profileRepo.findOne({ const profile = await this.profileRepo.findOne({

View file

@ -114,6 +114,28 @@ export async function getUser(userId: string) {
return await res.json(); return await res.json();
} }
/**
* Get keycloak user by Username (citizenId)
*
* Client must have permission to manage realm's user
*
* @returns user if success, false otherwise.
*/
export async function getUserByUsername(citizenId: string) {
const res = await fetch(`${KC_URL}/admin/realms/${KC_REALMS}/users?username=${citizenId}`, {
// prettier-ignore
headers: {
"authorization": `Bearer ${await getToken()}`,
"content-type": `application/json`,
},
}).catch((e) => console.log("Keycloak Error: ", e));
if (!res) return false;
if (!res.ok) {
return Boolean(console.error("Keycloak Error Response: ", await res.json()));
}
return await res.json();
}
/** /**
* Get keycloak user list * Get keycloak user list
* *
@ -476,7 +498,7 @@ export async function getUserRoles(userId: string) {
*/ */
export async function addUserRoles(userId: string, roles: { id: string; name: string }[]) { export async function addUserRoles(userId: string, roles: { id: string; name: string }[]) {
const res = await fetch( const res = await fetch(
`${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}/role-mappings/realm`, `${KC_URL}/admin/realms/${KC_REALMS}/users/${userId}`,
{ {
// prettier-ignore // prettier-ignore
headers: { headers: {