Yaltopia-Tickets-App/lib/auth-guards.ts

47 lines
1.3 KiB
TypeScript

import { RouteGuard, GuardResult } from "@sirou/core";
import { useAuthStore } from "./auth-store";
/**
* Authentication Guard
* Prevents unauthenticated users from accessing protected routes.
*/
export const authGuard: RouteGuard = {
name: "auth",
execute: async ({ route, meta }): Promise<GuardResult> => {
const { isAuthenticated } = useAuthStore.getState();
const requiresAuth = meta?.requiresAuth ?? false;
console.log(
`[AUTH_GUARD] checking: "${route}" (requiresAuth: ${requiresAuth}, auth: ${isAuthenticated})`,
);
if (requiresAuth && !isAuthenticated) {
console.log(`[AUTH_GUARD] DENIED -> redirect /login`);
return {
allowed: false,
redirect: "login", // Use name, not path
};
}
return { allowed: true };
},
};
export const guestGuard: RouteGuard = {
name: "guest",
execute: async ({ meta }): Promise<GuardResult> => {
const { isAuthenticated } = useAuthStore.getState();
const guestOnly = meta?.guestOnly ?? false;
if (guestOnly && isAuthenticated) {
console.log(`[GUEST_GUARD] Authenticated user blocked -> redirect /`);
return {
allowed: false,
redirect: "(tabs)", // Redirect to home if already logged in
};
}
return { allowed: true };
},
};