corrad-af-2024/server/utils/authentik.js
Md Afiq Iskandar ef5526baf1 Refactor Application Creation and Management Logic
- Simplified the application creation process by consolidating form fields and enhancing validation.
- Updated the create application page to streamline user experience with clearer provider options and improved layout.
- Implemented SweetAlert for success and error notifications during user actions, replacing traditional alerts.
- Enhanced the applications index page with dynamic filtering and improved data fetching from the Authentik API.
- Refactored API endpoints to utilize slugs for application identification, ensuring consistency with Authentik's structure.
- Improved authentication handling by updating the requireAuth utility to support cookie-based authentication.
2025-06-17 11:53:15 +08:00

84 lines
2.6 KiB
JavaScript

// Simplified Authentik API utilities
export const authentikFetch = async (endpoint, options = {}) => {
const config = useRuntimeConfig();
const AUTHENTIK_BASE_URL = `${config.public.authentikUrl}/api/v3`;
// Debug: Check if token exists
if (!config.authentik?.apiToken) {
console.error('❌ AUTHENTIK_API_TOKEN is missing from environment variables');
throw createError({
statusCode: 500,
message: 'Authentik API token not configured. Please set AUTHENTIK_API_TOKEN in your .env file'
});
}
const defaultOptions = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.authentik.apiToken}`
}
};
try {
const response = await $fetch(`${AUTHENTIK_BASE_URL}${endpoint}`, {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers
}
});
return response;
} catch (error) {
// Only log errors that need attention
console.error(`❌ Authentik API Error: ${endpoint} - ${error.message}`);
// More specific error messages
if (error.response?.status === 403) {
throw createError({
statusCode: 403,
message: 'Authentik API token does not have sufficient permissions. Please check your token configuration in Authentik admin.',
data: error.data || error.response?._data
});
}
if (error.response?.status === 401) {
throw createError({
statusCode: 401,
message: 'Authentik API token is invalid or expired. Please check AUTHENTIK_API_TOKEN in your .env file.',
data: error.data || error.response?._data
});
}
throw createError({
statusCode: error.response?.status || 500,
message: error.message || 'Failed to communicate with Authentik API',
data: error.data || error.response?._data
});
}
};
// Only keep essential helper functions - no over-engineering
export const getAuthentikUser = async (userId) => {
return await authentikFetch(`/core/users/${userId}/`);
};
export const getAuthentikGroups = async () => {
return await authentikFetch('/core/groups/');
};
// Clear Authentik policy cache
export const clearAuthentikCache = async () => {
try {
console.log('🧹 Clearing Authentik policy cache...');
const response = await authentikFetch('/policies/all/cache_clear/', {
method: 'POST'
});
console.log('✅ Authentik cache cleared successfully');
return { success: true, message: 'Cache cleared successfully' };
} catch (error) {
console.error('❌ Failed to clear Authentik cache:', error);
throw error;
}
};