import { type Request, type RequestHandler, type Response } from "express"; import KeycloakConnect from "keycloak-connect"; import { inject } from "../../../infrastructure/di/index.js"; import { Injectable } from "../../../infrastructure/di/injectable-decorator.js"; import { sessionStore } from "../../../infrastructure/sessionHandler.js"; import { EnvironmentService } from "../../environmentService.js"; //TODO transform into service and load config based on environment (see keycloak-admin) export const KC_SECURITY_NAME = "bearerAuth"; @Injectable() export class KeycloakUser { private readonly environment = inject(EnvironmentService); private readonly keycloakConnect: Promise; private async getConfig() { if (this.environment.isDev()) { const config = await import("./keycloak.dev.json", { with: { type: "json" }, }); return config.default; } else { const config = await import("./keycloak.prod.json", { with: { type: "json" }, }); return config.default; } } public constructor() { this.keycloakConnect = new Promise(async resolve => { const config = await this.getConfig(); const client = new KeycloakConnect({ store: sessionStore }, config); client.authenticated=(r)=>{ console.dir(r); }; resolve(client); }); } public async checkRoles( roles: string[], request: Request, response: Response, ) { const client = await this.keycloakConnect; const grant = await client.getGrant(request, response ?? ({} as any)); return roles.every(role => grant.access_token?.hasRealmRole(role)); } public async middleware(): Promise { const client = await this.keycloakConnect; return client.middleware(); } public async getUid(request: Request, response?: Response): Promise{ const client = await this.keycloakConnect; const grant = await client.getGrant(request, response ?? ({} as any)); return (grant.access_token as any)?.content?.sub; } }