From d3f65bd4c81430e9f13842c4c490773acb917428 Mon Sep 17 00:00:00 2001 From: kittapath Date: Tue, 12 Nov 2024 09:11:39 +0700 Subject: [PATCH] update role user --- src/controllers/UserController.ts | 205 +++++++++++++++++++++--------- 1 file changed, 144 insertions(+), 61 deletions(-) diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index de96c849..f63e0209 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -36,7 +36,10 @@ import { Profile } from "../entities/Profile"; import { ProfileEmployee } from "../entities/ProfileEmployee"; import { RequestWithUser } from "../middlewares/user"; import HttpSuccess from "../interfaces/http-success"; -import { Brackets } from "typeorm"; +import { Brackets, In } from "typeorm"; +import HttpError from "../interfaces/http-error"; +import HttpStatus from "../interfaces/http-status"; +import { RoleKeycloak } from "../entities/RoleKeycloak"; // import * as io from "../lib/websocket"; // import elasticsearch from "../elasticsearch"; // import { StorageFolder } from "../interfaces/storage-fs"; @@ -55,6 +58,7 @@ function stripLeadingSlash(str: string) { export class KeycloakController extends Controller { private profileRepo = AppDataSource.getRepository(Profile); private profileEmpRepo = AppDataSource.getRepository(ProfileEmployee); + private roleKeycloakRepo = AppDataSource.getRepository(RoleKeycloak); @Get("user/{id}") async getUser(@Path("id") id: string) { @@ -191,11 +195,26 @@ export class KeycloakController extends Controller { where: { keycloak: userId, }, + relations: ["roleKeycloaks"], }); - - if (profile) { + if (!profile) { + const profileEmp = await this.profileEmpRepo.findOne({ + where: { + keycloak: userId, + }, + relations: ["roleKeycloaks"], + }); + if (!profileEmp) { + } else { + const null_: any = null; + profileEmp.keycloak = null_; + profileEmp.roleKeycloaks = []; + await this.profileEmpRepo.save(profileEmp); + } + } else { const null_: any = null; profile.keycloak = null_; + profile.roleKeycloaks = []; await this.profileRepo.save(profile); } } @@ -214,6 +233,28 @@ export class KeycloakController extends Controller { @Post("{userId}/role") async addRole(@Path() userId: string, @Body() body: { role: string[] }) { + const roleKeycloak = await this.roleKeycloakRepo.find({ + where: { id: In(body.role) }, + }); + const profile = await this.profileRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (!profile) { + const profileEmp = await this.profileEmpRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + profileEmp.roleKeycloaks = Array.from( + new Set([...profileEmp.roleKeycloaks, ...roleKeycloak]), + ); + this.profileEmpRepo.save(profileEmp); + } else { + profile.roleKeycloaks = Array.from(new Set([...profile.roleKeycloaks, ...roleKeycloak])); + this.profileRepo.save(profile); + } + const list = await getRoles(); if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); @@ -228,6 +269,23 @@ export class KeycloakController extends Controller { @Delete("{userId}/role/{roleId}") async deleteRole(@Path() userId: string, @Path() roleId: string) { + const profile = await this.profileRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (!profile) { + const profileEmp = await this.profileEmpRepo.findOne({ + where: { keycloak: userId }, + relations: ["roleKeycloaks"], + }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + profileEmp.roleKeycloaks = profileEmp.roleKeycloaks.filter((x) => x.id != roleId); + this.profileEmpRepo.save(profileEmp); + } else { + profile.roleKeycloaks = profile.roleKeycloaks.filter((x) => x.id != roleId); + this.profileRepo.save(profile); + } + const list = await getRoles(); if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); @@ -360,69 +418,68 @@ export class KeycloakController extends Controller { @Query() type: string = "", ) { // sort by org - let profiles: any; + let profiles: any = []; let total: any; - if (type == "OFFICER") { + if (type.trim().toUpperCase() == "OFFICER") { [profiles, total] = await this.profileRepo - .createQueryBuilder("profile") - .leftJoinAndSelect("profile.roleKeycloaks", "roleKeycloaks") - .where("profile.keycloak IS NOT NULL AND profile.keycloak != ''") - .andWhere( - new Brackets((qb) => { - qb.orWhere(keyword != null && keyword != "" ? `profile.citizenId like '%${keyword}%'` : "1=1") - .orWhere(keyword != null && keyword != "" ? `profile.email like '%${keyword}%'` : "1=1") - .orWhere( - keyword != null && keyword != "" - ? `CONCAT(profile.prefix, profile.firstName," ",profile.lastName) like '%${keyword}%'` - : "1=1", - ) - }), - ) - .skip((page - 1) * pageSize) - .take(pageSize) - .getManyAndCount(); - } - else if (type == "EMPLOYEE") { + .createQueryBuilder("profile") + .leftJoinAndSelect("profile.roleKeycloaks", "roleKeycloaks") + .where("profile.keycloak IS NOT NULL AND profile.keycloak != ''") + .andWhere( + new Brackets((qb) => { + qb.orWhere( + keyword != null && keyword != "" ? `profile.citizenId like '%${keyword}%'` : "1=1", + ) + .orWhere( + keyword != null && keyword != "" ? `profile.email like '%${keyword}%'` : "1=1", + ) + .orWhere( + keyword != null && keyword != "" + ? `CONCAT(profile.prefix, profile.firstName," ",profile.lastName) like '%${keyword}%'` + : "1=1", + ); + }), + ) + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); + } else if (type.trim().toUpperCase() == "EMPLOYEE") { [profiles, total] = await this.profileEmpRepo - .createQueryBuilder("profileEmployee") - .leftJoinAndSelect("profileEmployee.roleKeycloaks", "roleKeycloaks") - .where("profileEmployee.keycloak IS NOT NULL AND profileEmployee.keycloak != ''") - .andWhere( - new Brackets((qb) => { - qb.orWhere(keyword != null && keyword != "" ? `profileEmployee.citizenId like '%${keyword}%'` : "1=1") - .orWhere(keyword != null && keyword != "" ? `profileEmployee.email like '%${keyword}%'` : "1=1") - .orWhere( - keyword != null && keyword != "" - ? `CONCAT(profileEmployee.prefix, profileEmployee.firstName," ",profileEmployee.lastName) like '%${keyword}%'` - : "1=1", - ) - }), - ) - .skip((page - 1) * pageSize) - .take(pageSize) - .getManyAndCount(); + .createQueryBuilder("profileEmployee") + .leftJoinAndSelect("profileEmployee.roleKeycloaks", "roleKeycloaks") + .where("profileEmployee.keycloak IS NOT NULL AND profileEmployee.keycloak != ''") + .andWhere( + new Brackets((qb) => { + qb.orWhere( + keyword != null && keyword != "" + ? `profileEmployee.citizenId like '%${keyword}%'` + : "1=1", + ) + .orWhere( + keyword != null && keyword != "" + ? `profileEmployee.email like '%${keyword}%'` + : "1=1", + ) + .orWhere( + keyword != null && keyword != "" + ? `CONCAT(profileEmployee.prefix, profileEmployee.firstName," ",profileEmployee.lastName) like '%${keyword}%'` + : "1=1", + ); + }), + ) + .skip((page - 1) * pageSize) + .take(pageSize) + .getManyAndCount(); } - else { - return new HttpSuccess({ data: [], total: 0 }); - } - - const _profiles = profiles.map((_data:any) => ({ - id: _data.id, + + const _profiles = profiles.map((_data: any) => ({ + id: _data.keycloak, firstname: _data.firstName, lastname: _data.lastName, email: _data.email, username: _data.citizenId, citizenId: _data.citizenId, - roles: _data.roleKeycloaks.length > 0 - ? _data.roleKeycloaks.map((x:any) => ({ - id: x.id, - name: x.name, - description: x.description, - composite: x.composite, - clientRole: x.clientRole, - containerId: x.containerId, - })) - : [], + roles: _data.roleKeycloaks, enabled: _data.isActive, })); return new HttpSuccess({ data: _profiles, total }); @@ -468,15 +525,41 @@ export class KeycloakController extends Controller { @Get("user/role/{id}") async getRoleUser(@Path("id") id: string) { - const result = await getRoleMappings(id); - if (!result) { - throw new Error("Role mappings not found"); + const profile = await this.profileRepo.findOne({ + where: { keycloak: id }, + relations: ["roleKeycloaks"], + }); + if (!profile) { + const profileEmp = await this.profileEmpRepo.findOne({ + where: { keycloak: id }, + relations: ["roleKeycloaks"], + }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + return profileEmp.roleKeycloaks; } - return result; + // const result = await getRoleMappings(id); + // if (!result) { + // throw new Error("Role mappings not found"); + // } + return profile.roleKeycloaks; } @Put("user/{userId}/enableStatus/{status}") //#log? async changeEnableStatus(@Path() userId: string, @Path() status: boolean) { + const profile = await this.profileRepo.findOne({ + where: { keycloak: userId }, + }); + if (!profile) { + const profileEmp = await this.profileEmpRepo.findOne({ + where: { keycloak: userId }, + }); + if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); + profileEmp.isActive = status; + this.profileEmpRepo.save(profileEmp); + } else { + profile.isActive = status; + this.profileRepo.save(profile); + } const result = await enableStatus(userId, status); if (!result) { throw new Error("Failed. Cannot change enable status.");