jws-backend/src/controllers/00-keycloak-controller.ts

56 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Body, Controller, Delete, Get, Path, Post, Route, Security, Tags } from "tsoa";
2025-04-22 14:02:36 +07:00
import { addUserRoles, getGroup, listRole, removeUserRoles } from "../services/keycloak";
2024-06-06 09:42:02 +07:00
@Route("api/v1/keycloak")
2024-04-05 15:24:24 +07:00
@Tags("Single-Sign On")
@Security("keycloak")
export class KeycloakController extends Controller {
@Get("role")
async getRole() {
2024-07-01 13:24:02 +07:00
const role = await listRole();
if (Array.isArray(role))
return role.filter(
(a) =>
2024-08-13 20:25:32 +07:00
!["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[] }) {
2024-07-01 13:24:02 +07:00
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) {
2024-07-01 13:24:02 +07:00
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.");
}
2025-04-22 14:02:36 +07:00
@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;
}
}