diff --git a/src/controllers/UserController.ts b/src/controllers/UserController.ts index 4902ce0f..86b44ef4 100644 --- a/src/controllers/UserController.ts +++ b/src/controllers/UserController.ts @@ -47,6 +47,11 @@ import { RoleKeycloak } from "../entities/RoleKeycloak"; import { addLogSequence } from "../interfaces/utils"; import { OrgRevision } from "../entities/OrgRevision"; import { Uuid } from "@elastic/elasticsearch/lib/api/types"; +import { promisify } from "util"; + +const REDIS_HOST = process.env.REDIS_HOST; +const REDIS_PORT = process.env.REDIS_PORT; +const redis = require("redis"); // import * as io from "../lib/websocket"; // import elasticsearch from "../elasticsearch"; // import { StorageFolder } from "../interfaces/storage-fs"; @@ -352,6 +357,8 @@ export class KeycloakController extends Controller { where: { keycloak: userId }, relations: ["roleKeycloaks"], }); + let profileId: string | undefined; + if (!profile) { const profileEmp = await this.profileEmpRepo.findOne({ where: { keycloak: userId, employeeClass: "PERM" }, @@ -359,10 +366,12 @@ export class KeycloakController extends Controller { }); if (!profileEmp) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); profileEmp.roleKeycloaks = profileEmp.roleKeycloaks.filter((x) => x.id != roleId); - this.profileEmpRepo.save(profileEmp); + await this.profileEmpRepo.save(profileEmp); + profileId = profileEmp.id; } else { profile.roleKeycloaks = profile.roleKeycloaks.filter((x) => x.id != roleId); - this.profileRepo.save(profile); + await this.profileRepo.save(profile); + profileId = profile.id; } const list = await getRoles(); @@ -374,6 +383,38 @@ export class KeycloakController extends Controller { list.filter((v) => roleId === v.id), ); if (!result) throw new Error("Failed. Cannot remove user's role."); + + if (profileId) { + let redisClient: any; + let quitAsync: any; + try { + redisClient = redis.createClient({ + host: REDIS_HOST, + port: REDIS_PORT, + }); + const delAsync = promisify(redisClient.del).bind(redisClient); + quitAsync = promisify(redisClient.quit).bind(redisClient); + + const [roleDeleted, menuDeleted] = await Promise.all([ + delAsync("role_" + profileId), + delAsync("menu_" + profileId), + ]); + + if (roleDeleted === 0) { + console.warn(`Redis key not found: role_${profileId}`); + } + if (menuDeleted === 0) { + console.warn(`Redis key not found: menu_${profileId}`); + } + } catch (error) { + console.error(`Failed to delete Redis cache for profile ${profileId}:`, error); + } finally { + if (quitAsync) { + await quitAsync(); + } + } + } + return new HttpSuccess(); }