2025-08-07 12:28:41 +02:00
|
|
|
export default defineEventHandler(async (event) => {
|
2025-08-31 18:28:38 +02:00
|
|
|
console.log('📊 Admin stats requested at:', new Date().toISOString());
|
2025-08-07 12:28:41 +02:00
|
|
|
|
|
|
|
|
try {
|
2025-08-07 16:20:05 +02:00
|
|
|
// Check if user is admin
|
2025-08-07 12:28:41 +02:00
|
|
|
const sessionManager = createSessionManager();
|
|
|
|
|
const cookieHeader = getHeader(event, 'cookie');
|
|
|
|
|
const session = sessionManager.getSession(cookieHeader);
|
|
|
|
|
|
|
|
|
|
if (!session || session.user.tier !== 'admin') {
|
|
|
|
|
console.warn('🚨 Unauthorized admin stats access attempt');
|
|
|
|
|
throw createError({
|
|
|
|
|
statusCode: 403,
|
|
|
|
|
statusMessage: 'Admin access required'
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('✅ Admin access verified for user:', session.user.email);
|
|
|
|
|
|
2025-08-31 18:28:38 +02:00
|
|
|
// Get real user count from Keycloak
|
|
|
|
|
let userCount = 0;
|
|
|
|
|
try {
|
|
|
|
|
const { createKeycloakAdminClient } = await import('~/server/utils/keycloak-admin');
|
|
|
|
|
const keycloakAdmin = createKeycloakAdminClient();
|
|
|
|
|
userCount = await keycloakAdmin.getUserCount(false); // Exclude service accounts
|
|
|
|
|
console.log('✅ Retrieved real user count from Keycloak:', userCount);
|
|
|
|
|
} catch (keycloakError: any) {
|
|
|
|
|
console.error('⚠️ Failed to get user count from Keycloak:', keycloakError);
|
|
|
|
|
// Instead of returning mock data, return 0 or null to indicate data unavailable
|
|
|
|
|
console.log('⚠️ User count unavailable, returning 0');
|
|
|
|
|
userCount = 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Return stats with real data
|
2025-08-07 12:28:41 +02:00
|
|
|
const stats = {
|
2025-08-31 18:28:38 +02:00
|
|
|
// Real user count from Keycloak (0 if unavailable)
|
|
|
|
|
userCount: userCount,
|
2025-08-07 15:51:16 +02:00
|
|
|
|
2025-08-31 18:28:38 +02:00
|
|
|
// Basic portal health
|
2025-08-07 16:20:05 +02:00
|
|
|
portalStatus: 'online',
|
2025-08-31 18:28:38 +02:00
|
|
|
lastUpdate: new Date().toISOString(),
|
|
|
|
|
|
|
|
|
|
// Add flag to indicate if data is from cache or live
|
|
|
|
|
dataSource: userCount > 0 ? 'live' : 'unavailable'
|
2025-08-07 12:28:41 +02:00
|
|
|
};
|
|
|
|
|
|
2025-08-31 18:28:38 +02:00
|
|
|
console.log('✅ Admin stats retrieved successfully:', stats);
|
2025-08-07 12:28:41 +02:00
|
|
|
return stats;
|
|
|
|
|
|
|
|
|
|
} catch (error: any) {
|
|
|
|
|
console.error('❌ Admin stats error:', error);
|
|
|
|
|
|
|
|
|
|
if (error.statusCode) {
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw createError({
|
|
|
|
|
statusCode: 500,
|
2025-08-07 16:20:05 +02:00
|
|
|
statusMessage: 'Failed to retrieve admin statistics'
|
2025-08-07 12:28:41 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
});
|