"use client"; import React from "react"; import { RefreshCw } from "lucide-react"; import { usePathname, useRouter } from "next/navigation"; import { useAuth } from "@/components/auth/authContext"; import { shouldRedirectToProfileForPasswordChange, buildMustChangePasswordRedirectUrl, resolveMustChangePasswordResumePath, } from "@/lib/frontend/auth/mustChangePasswordGate"; import { Button } from "@/components/ui/button"; import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert"; import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter, } from "@/components/ui/card"; export default function AuthGate({ children }) { const router = useRouter(); const pathname = usePathname() || "/"; const { status, user, error, retry } = useAuth(); const canRetry = typeof retry === "function"; const isAuthenticated = status === "authenticated" && user; const mustChangePassword = isAuthenticated && user.mustChangePassword === true; const currentSearch = typeof window !== "undefined" ? window.location.search || "" : ""; const currentPathWithSearch = `${pathname}${currentSearch}`; const mustChangePasswordRedirectUrl = buildMustChangePasswordRedirectUrl( currentPathWithSearch, ); const shouldForceProfileRedirect = isAuthenticated ? shouldRedirectToProfileForPasswordChange({ pathname, mustChangePassword, }) : false; const resumePathAfterPasswordChange = isAuthenticated ? resolveMustChangePasswordResumePath({ pathname, searchParams: typeof window !== "undefined" ? new URLSearchParams(window.location.search || "") : null, mustChangePassword, }) : null; React.useEffect(() => { if (!shouldForceProfileRedirect) return; router.replace(mustChangePasswordRedirectUrl); }, [shouldForceProfileRedirect, mustChangePasswordRedirectUrl, router]); React.useEffect(() => { if (!resumePathAfterPasswordChange) return; router.replace(resumePathAfterPasswordChange); }, [resumePathAfterPasswordChange, router]); if (status === "authenticated") { if (shouldForceProfileRedirect) return null; if (resumePathAfterPasswordChange) return null; return children; } if (status === "error") { return ( Sitzungsprüfung fehlgeschlagen Die Sitzung konnte nicht geprüft werden. Fehler {error || "Bitte prüfen Sie Ihre Verbindung und versuchen Sie es erneut."} ); } // "unauthenticated" -> redirect happens in AuthProvider. // Keeping this message is fine because TopNav indicator is not shown in this state. if (status === "unauthenticated") { return ( Weiterleitung Sie werden zum Login weitergeleitet.

Bitte warten…

); } // Default: loading (or unknown) // RHL-032: // Do not render a second "session checking" UI here. // The TopNav SessionIndicator is the single source of feedback. return null; }