Files
Web-Antrean/middleware/auth.ts

55 lines
2.2 KiB
TypeScript

import { defineNuxtRouteMiddleware, navigateTo } from '#app';
import type { RouteLocationNormalized } from 'vue-router';
// Import the useAuth composable (it will be auto-imported, but this helps TypeScript/VS Code)
import { useAuth } from '~/composables/useAuth';
// NOTE: We don't need the interfaces here anymore, as useAuth handles the typing.
export default defineNuxtRouteMiddleware(async (to: RouteLocationNormalized) => {
console.log('🛡️ Auth middleware triggered for:', to.path);
// Allow the login page to handle its own checks without redirection loops
if (to.path === '/LoginPage') {
console.log('⏭️ Allowing access to LoginPage');
return;
}
// Skip auth check if it's the development server side render pass.
// Although we still recommend using the checkAuth() composable for better SSR handling.
if (process.server && process.env.NODE_ENV === 'development') {
console.log('⏭️ Skipping intensive check on server-side during development');
// Using the composable here ensures it is registered correctly, even if we skip the main check
useAuth();
return;
}
// Check for the authentication signal from a successful login redirect
const isAuthRedirect: boolean = to.query.authenticated === 'true';
if (isAuthRedirect) {
console.log('⏳ Client-side is processing a new login session, allowing the route to load...');
return navigateTo({ path: to.path, query: {} }, { replace: true });
}
try {
const { checkAuth } = useAuth();
console.log('🔍 Checking authentication status using useAuth...');
// Use the composable's function to check the session
const user = await checkAuth();
if (user) {
console.log('✅ User is authenticated:', user.name || user.preferred_username || user.email);
return;
} else {
console.log('❌ No valid session found, redirecting to login');
// If checkAuth fails, it already cleared the user state. Redirect.
return navigateTo('/LoginPage');
}
} catch (error) {
console.error('❌ Auth middleware error:', error);
console.log('🔄 Redirecting to login due to error');
return navigateTo('/LoginPage');
}
});