import { useAuthStore } from '@/stores/auth'; import { router } from '@inertiajs/vue3'; import { computed, onMounted, ref } from 'vue'; /** * Composable to protect pages that require authentication * Usage: Call this in the setup of any component that requires auth * * Example: * ```vue * * ``` * * Note: With the global middleware setup in app.ts, this composable is optional. * The global middleware will handle redirects automatically. * Use this composable if you need to show loading states or access auth data. */ export function useAuthGuard(redirectTo: string = '/login') { const authStore = useAuthStore(); const isChecking = ref(true); onMounted(async () => { const isAuthenticated = await authStore.checkAuth(); isChecking.value = false; if (!isAuthenticated) { router.get(redirectTo, {}, { replace: true }); } }); return { isAuthenticated: computed(() => authStore.isAuthenticated), user: computed(() => authStore.currentUser), loading: computed(() => authStore.loading), isChecking, }; } /** * Composable to protect pages that should only be accessible to guests * (e.g., login, register pages) * * Example: * ```vue * * ``` * * Note: With the global middleware setup in app.ts, this composable is optional. * The global middleware will handle redirects automatically. * Use this composable if you need to show loading states. */ export function useGuestGuard(redirectTo: string = '/dashboard') { const authStore = useAuthStore(); const isChecking = ref(true); onMounted(async () => { const isAuthenticated = await authStore.checkAuth(); isChecking.value = false; if (isAuthenticated) { router.get(redirectTo, {}, { replace: true }); } }); return { isAuthenticated: computed(() => authStore.isAuthenticated), isChecking, }; } /** * Simple composable to access auth state without guards * * Example: * ```vue * * ``` */ export function useAuth() { const authStore = useAuthStore(); return { user: computed(() => authStore.currentUser), isAuthenticated: computed(() => authStore.isAuthenticated), loading: computed(() => authStore.loading), error: computed(() => authStore.error), login: authStore.login, logout: authStore.logout, checkAuth: authStore.checkAuth, }; }