|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect } from 'react'; |
| 4 | +import { useSession } from 'next-auth/react'; |
| 5 | +import { useRouter } from 'next/navigation'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Wrapper component that redirects authenticated users to their respective dashboards. |
| 9 | + * This prevents users from seeing the landing page after logging in. |
| 10 | + */ |
| 11 | +export function LandingPageWrapper({ children }: { children: React.ReactNode }) { |
| 12 | + const { data: session, status } = useSession(); |
| 13 | + const router = useRouter(); |
| 14 | + |
| 15 | + useEffect(() => { |
| 16 | + // Only redirect if we're certain the user is authenticated with valid data |
| 17 | + if (status === 'authenticated' && session?.user?.id && session.user.role) { |
| 18 | + // Redirect based on user role |
| 19 | + const redirectMap: Record<string, string> = { |
| 20 | + admin: '/admin', |
| 21 | + doctor: '/doctor', |
| 22 | + nurse: '/nurse', |
| 23 | + pharmacist: '/pharmacist', |
| 24 | + 'lab-tech': '/lab-tech', |
| 25 | + receptionist: '/receptionist', |
| 26 | + emergency: '/emergency', |
| 27 | + }; |
| 28 | + |
| 29 | + const role = session.user.role.toLowerCase(); |
| 30 | + const redirectPath = redirectMap[role] || '/admin'; |
| 31 | + |
| 32 | + // Use replace to prevent back button issues |
| 33 | + router.replace(redirectPath); |
| 34 | + } |
| 35 | + }, [status, session, router]); |
| 36 | + |
| 37 | + // While session is loading, show nothing |
| 38 | + if (status === 'loading') { |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + // If authenticated, show nothing (effect will handle redirect) |
| 43 | + if (status === 'authenticated') { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + // Only show landing page for unauthenticated users |
| 48 | + return <>{children}</>; |
| 49 | +} |
0 commit comments