64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
import { defineNuxtRouteMiddleware, navigateTo } from '#app';
|
|
import type { RouteLocationNormalized } from 'vue-router';
|
|
import { useAuth } from '~/composables/useAuth';
|
|
|
|
export default defineNuxtRouteMiddleware(async (to: RouteLocationNormalized) => {
|
|
console.log('🛡️ Auth middleware triggered for:', to.path);
|
|
|
|
// Check for bypass flag (from keyboard shortcut)
|
|
if (process.client) {
|
|
const bypassFlag = sessionStorage.getItem('bypassRootRedirect');
|
|
if (bypassFlag === 'true' && to.path === '/') {
|
|
console.log('🔑 Bypass flag detected - allowing root access');
|
|
// Clear the flag immediately to prevent future bypasses
|
|
sessionStorage.removeItem('bypassRootRedirect');
|
|
return; // Allow access without any redirect
|
|
}
|
|
}
|
|
|
|
// Redirect root path to LoginPage
|
|
if (to.path === '/') {
|
|
console.log('🔄 Redirecting from root to LoginPage');
|
|
return navigateTo('/LoginPage', { replace: true });
|
|
}
|
|
|
|
// 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.
|
|
if (process.server && process.env.NODE_ENV === 'development') {
|
|
console.log('⏭️ Skipping intensive check on server-side during development');
|
|
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...');
|
|
|
|
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');
|
|
return navigateTo('/LoginPage');
|
|
}
|
|
} catch (error) {
|
|
console.error('❌ Auth middleware error:', error);
|
|
console.log('🔄 Redirecting to login due to error');
|
|
return navigateTo('/LoginPage');
|
|
}
|
|
}); |