Files
2026-02-23 14:29:56 +07:00

88 lines
2.4 KiB
TypeScript

import { ref } from 'vue';
interface KeycloakRole {
id: string;
name: string;
description: string;
composite: boolean;
clientRole: boolean;
containerId: string;
}
export const useKeycloakRoles = () => {
const roles = ref<KeycloakRole[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
const config = useRuntimeConfig();
const fetchRoles = async () => {
loading.value = true;
error.value = null;
try {
// Get access token from localStorage or session
const accessToken = localStorage.getItem('accessToken');
if (!accessToken) {
throw new Error('Access token not found');
}
if(!config.public.keycloakClientUuid) {
throw new Error('Keycloak client UUID is not configured');
}
if(!config.public.keycloakAdminRealmUrl) {
throw new Error('Keycloak admin realm URL is not configured');
}
const response = await fetch(
`${config.public.keycloakAdminRealmUrl}/clients/${config.public.keycloakClientUuid}/roles`,
{
method: 'GET',
headers: {
'accept': 'application/json, text/plain, */*',
'authorization': `Bearer ${accessToken}`,
'content-type': 'application/json'
}
}
);
if (!response.ok) {
throw new Error(`Failed to fetch roles: ${response.statusText}`);
}
const data = await response.json();
roles.value = data;
return data;
} catch (err) {
error.value = err instanceof Error ? err.message : 'Unknown error';
console.error('Error fetching Keycloak roles:', err);
return [];
} finally {
loading.value = false;
}
};
const getRoleNames = (): string[] => {
return roles.value.map(role => role.name);
};
const getRoleOptions = () => {
return roles.value.map(role => ({
value: role.name,
title: role.name,
description: role.description
}));
};
return {
roles,
loading,
error,
fetchRoles,
getRoleNames,
getRoleOptions
};
};