99 lines
2.5 KiB
TypeScript
99 lines
2.5 KiB
TypeScript
import { useAuthStore } from '@/stores/auth';
|
|
import { router } from '@inertiajs/vue3';
|
|
|
|
/**
|
|
* Protected routes that require authentication
|
|
*/
|
|
const protectedRoutes = [
|
|
'/dashboard',
|
|
'/profile',
|
|
'/paiement',
|
|
'/cards',
|
|
'/agenda',
|
|
'/checkout',
|
|
'/payments',
|
|
];
|
|
|
|
/**
|
|
* Guest-only routes (redirect if authenticated)
|
|
*/
|
|
const guestRoutes = [
|
|
'/login',
|
|
'/register',
|
|
'/password/request',
|
|
'/password/reset',
|
|
];
|
|
|
|
/**
|
|
* Check if a URL matches any of the route patterns
|
|
*/
|
|
function matchesRoute(url: string, routes: string[]): boolean {
|
|
return routes.some(route => url.startsWith(route));
|
|
}
|
|
|
|
/**
|
|
* Setup Inertia.js navigation guards
|
|
* This uses Inertia's event system to intercept navigation
|
|
*/
|
|
export function setupAuthGuards(): void {
|
|
const authStore = useAuthStore();
|
|
|
|
// Initialize auth state on app load
|
|
authStore.checkAuth().catch(() => {
|
|
// Silent fail - user is not authenticated
|
|
});
|
|
|
|
// Intercept Inertia navigation before it happens
|
|
router.on('before', async (event) => {
|
|
const url = event.detail.visit.url.pathname;
|
|
|
|
// Check if trying to access a protected route
|
|
if (matchesRoute(url, protectedRoutes)) {
|
|
const isAuthenticated = await authStore.checkAuth();
|
|
|
|
if (!isAuthenticated && url !== '/login') {
|
|
// Prevent the navigation and redirect to login
|
|
event.preventDefault();
|
|
router.get('/login', {}, {
|
|
preserveState: false,
|
|
replace: true
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Check if trying to access a guest-only route
|
|
if (matchesRoute(url, guestRoutes)) {
|
|
const isAuthenticated = await authStore.checkAuth();
|
|
|
|
if (isAuthenticated && url !== '/dashboard') {
|
|
// Prevent the navigation and redirect to dashboard
|
|
event.preventDefault();
|
|
router.get('/dashboard', {}, {
|
|
preserveState: false,
|
|
replace: true
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Add a protected route to the list
|
|
*/
|
|
export function addProtectedRoute(route: string): void {
|
|
if (!protectedRoutes.includes(route)) {
|
|
protectedRoutes.push(route);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Add a guest route to the list
|
|
*/
|
|
export function addGuestRoute(route: string): void {
|
|
if (!guestRoutes.includes(route)) {
|
|
guestRoutes.push(route);
|
|
}
|
|
}
|