jws-backend/src/controllers/00-keycloak-controller.ts
Kanjana 94c7de89eb
All checks were successful
Spell Check / Spell Check with Typos (push) Successful in 7s
add group from keycloak
2025-04-22 14:02:36 +07:00

55 lines
1.7 KiB
TypeScript

import { Body, Controller, Delete, Get, Path, Post, Route, Security, Tags } from "tsoa";
import { addUserRoles, getGroup, listRole, removeUserRoles } from "../services/keycloak";
@Route("api/v1/keycloak")
@Tags("Single-Sign On")
@Security("keycloak")
export class KeycloakController extends Controller {
@Get("role")
async getRole() {
const role = await listRole();
if (Array.isArray(role))
return role.filter(
(a) =>
!["uma_authorization", "offline_access", "default-roles", "system"].some((b) =>
a.name.includes(b),
),
);
throw new Error("Failed. Cannot get role.");
}
@Post("{userId}/role")
async addRole(@Path() userId: string, @Body() body: { role: string[] }) {
const list = await listRole();
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
const result = await addUserRoles(
userId,
list.filter((v) => body.role.includes(v.id)),
);
if (!result) throw new Error("Failed. Cannot set user's role.");
}
@Delete("{userId}/role/{roleId}")
async deleteRole(@Path() userId: string, @Path() roleId: string) {
const list = await listRole();
if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server.");
const result = await removeUserRoles(
userId,
list.filter((v) => roleId === v.id),
);
if (!result) throw new Error("Failed. Cannot remove user's role.");
}
@Get("group")
async getGroup() {
const group = await getGroup();
if (!Array.isArray(group)) throw new Error("Failed. Cannot get group(s) data from the server.");
return group;
}
}