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

75 lines
2.3 KiB
JavaScript

// Authentication utilities for API routes - Updated for cookie-based auth
export const requireAuth = async (event) => {
const config = useRuntimeConfig();
// Check for auth_token in cookies (Authentik sends via cookies)
const authToken = getCookie(event, 'auth_token');
if (!authToken) {
console.error('❌ No auth_token cookie found');
throw createError({
statusCode: 401,
message: 'No authentication token provided'
});
}
try {
// Decode JWT token locally (no API call needed since token contains all user info)
console.log('🔐 Decoding JWT token...');
// Simple JWT decode (split and base64 decode the payload)
const tokenParts = authToken.split('.');
if (tokenParts.length !== 3) {
throw new Error('Invalid JWT format');
}
// Decode the payload (second part of JWT)
const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64').toString());
// Check if token is expired
const now = Math.floor(Date.now() / 1000);
if (payload.exp && payload.exp < now) {
throw new Error('Token has expired');
}
// Extract user information from JWT payload
const userInfo = {
sub: payload.sub,
email: payload.email,
email_verified: payload.email_verified,
name: payload.name,
given_name: payload.given_name,
preferred_username: payload.preferred_username,
nickname: payload.nickname,
groups: payload.groups || [],
uid: payload.uid
};
console.log('✅ Authentication successful for user:', userInfo.preferred_username);
// Add user info to event context
event.context.auth = userInfo;
event.context.authToken = authToken;
return userInfo;
} catch (error) {
console.error('❌ Token verification failed:', error.message);
throw createError({
statusCode: 401,
message: 'Invalid or expired authentication token'
});
}
};
// Optional: Get current user from context (after requireAuth is called)
export const getCurrentUser = (event) => {
return event.context.auth;
};
// Optional: Check if user has specific permissions
export const hasPermission = (event, permission) => {
const user = getCurrentUser(event);
if (!user || !user.permissions) return false;
return user.permissions.includes(permission);
};