/** * Route Guard * * Provides route-level access control and guards. */ import { Logger } from '../../core/logger.js'; /** * RouteGuard - Route access control */ export class RouteGuard { constructor(name, guardFn) { this.name = name; this.guardFn = guardFn; } /** * Create a new RouteGuard */ static create(name, guardFn) { return new RouteGuard(name, guardFn); } /** * Execute guard */ async execute(to, from, context = {}) { try { const result = await this.guardFn(to, from, context); return { allowed: result !== false && result !== null, redirect: typeof result === 'string' ? result : null, reason: typeof result === 'object' && result.reason ? result.reason : null }; } catch (error) { Logger.error(`[RouteGuard] Guard "${this.name}" error:`, error); return { allowed: false, redirect: null, reason: error.message }; } } } /** * Built-in guards */ export const BuiltInGuards = { /** * Require authentication */ auth: RouteGuard.create('auth', async (to, from) => { // Check if user is authenticated // This would need to be implemented based on your auth system const isAuthenticated = checkAuth(); // Placeholder if (!isAuthenticated) { return '/login'; } return true; }), /** * Require guest (not authenticated) */ guest: RouteGuard.create('guest', async (to, from) => { const isAuthenticated = checkAuth(); // Placeholder if (isAuthenticated) { return '/'; } return true; }), /** * Require specific role */ role: (requiredRole) => RouteGuard.create('role', async (to, from) => { const userRole = getUserRole(); // Placeholder if (userRole !== requiredRole) { return '/unauthorized'; } return true; }), /** * Require permission */ permission: (requiredPermission) => RouteGuard.create('permission', async (to, from) => { const hasPermission = checkPermission(requiredPermission); // Placeholder if (!hasPermission) { return '/unauthorized'; } return true; }) }; // Placeholder functions (would be implemented based on auth system) function checkAuth() { // Implementation depends on auth system return false; } function getUserRole() { // Implementation depends on auth system return null; } function checkPermission(permission) { // Implementation depends on auth system return false; }