|
1 | 1 | "use client"; |
2 | 2 |
|
3 | | -import { useEffect, useState } from "react"; |
4 | | -import { handleIncomingRedirect } from "@inrupt/solid-client-authn-browser"; |
5 | | -import { getSession } from "../lib/helpers"; |
6 | | -import LoginPage from "./LoginPage"; |
| 3 | +import { useEffect, useState, Suspense } from "react"; |
| 4 | +import { useSolidAuth } from "@ldo/solid-react"; |
| 5 | +import { useSearchParams, useRouter, usePathname } from "next/navigation"; |
7 | 6 | import LoadingSpinner from "./shared/LoadingSpinner"; |
8 | | -import ErrorDisplay from "./shared/ErrorDisplay"; |
9 | 7 |
|
10 | 8 | interface AuthWrapperProps { |
11 | 9 | children: React.ReactNode; |
12 | 10 | } |
13 | 11 |
|
14 | | -export default function AuthWrapper({ children }: AuthWrapperProps) { |
15 | | - const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null); |
16 | | - const [isChecking, setIsChecking] = useState(true); |
17 | | - const [error, setError] = useState<Error | null>(null); |
| 12 | +// Check if there's any indication of a session in storage |
| 13 | +function hasSessionInStorage(): boolean { |
| 14 | + if (typeof window === "undefined") return false; |
| 15 | + |
| 16 | + try { |
| 17 | + const keys = Object.keys(localStorage); |
| 18 | + // Look for keys that might indicate a session exists |
| 19 | + return keys.some(key => |
| 20 | + key.includes("solidClientAuthn") || |
| 21 | + key.includes("solid-auth") || |
| 22 | + key.includes("oidc") || |
| 23 | + key.includes("session") |
| 24 | + ); |
| 25 | + } catch { |
| 26 | + return false; |
| 27 | + } |
| 28 | +} |
18 | 29 |
|
19 | | - useEffect(() => { |
20 | | - async function checkAuth() { |
21 | | - try { |
22 | | - setError(null); |
| 30 | +function AuthWrapperContent({ children }: AuthWrapperProps) { |
| 31 | + const { session } = useSolidAuth(); |
| 32 | + const searchParams = useSearchParams(); |
| 33 | + const router = useRouter(); |
| 34 | + const pathname = usePathname(); |
| 35 | + const [isCheckingSession, setIsCheckingSession] = useState(true); |
| 36 | + const [hasSessionIndicator, setHasSessionIndicator] = useState(() => hasSessionInStorage()); |
| 37 | + const [wasLoggedIn, setWasLoggedIn] = useState(false); |
23 | 38 |
|
24 | | - // First, handle any incoming OAuth redirect (processes code and state parameters) |
25 | | - await handleIncomingRedirect({ restorePreviousSession: true }); |
| 39 | + // Check if we're in the middle of an OAuth callback |
| 40 | + const isOAuthCallback = searchParams.has("code") || searchParams.has("state"); |
| 41 | + const isLoginPage = pathname === "/login"; |
26 | 42 |
|
27 | | - // Get the session instance after handling redirect |
28 | | - const session = getSession(); |
| 43 | + |
| 44 | + const hasSessionData = !!(session.webId || session.sessionId || session.clientAppId); |
29 | 45 |
|
30 | | - let isLoggedIn = session.info.isLoggedIn && !!session.info.webId; |
| 46 | + useEffect(() => { |
| 47 | + if (session.isLoggedIn) { |
| 48 | + setWasLoggedIn(true); |
| 49 | + } |
31 | 50 |
|
32 | | - // Check expiration if session exists |
33 | | - if (isLoggedIn && session.info.expirationDate) { |
34 | | - const expirationDate = new Date(session.info.expirationDate); |
35 | | - const now = new Date(); |
36 | | - if (expirationDate <= now) { |
37 | | - isLoggedIn = false; |
| 51 | + // If we're in an OAuth callback, keep checking until session is established |
| 52 | + // Don't redirect until session is confirmed |
| 53 | + if (isOAuthCallback) { |
| 54 | + setIsCheckingSession(true); |
| 55 | + |
| 56 | + if (session.isLoggedIn) { |
| 57 | + setIsCheckingSession(false); |
| 58 | + // Redirect to home after successful OAuth (remove OAuth params from URL) |
| 59 | + const redirectTimer = setTimeout(() => { |
| 60 | + if (typeof window !== "undefined") { |
| 61 | + window.location.href = "/"; |
38 | 62 | } |
39 | | - } |
40 | | - |
41 | | - setIsAuthenticated(isLoggedIn); |
42 | | - } catch (err) { |
43 | | - const errorMessage = |
44 | | - err instanceof Error ? err : new Error("Authentication check failed"); |
45 | | - setError(errorMessage); |
46 | | - setIsAuthenticated(false); |
47 | | - } finally { |
48 | | - setIsChecking(false); |
| 63 | + }, 200); |
| 64 | + return () => clearTimeout(redirectTimer); |
| 65 | + } else { |
| 66 | + // Session not yet established, keep waiting |
| 67 | + // Set a timeout to prevent infinite waiting (max 10 seconds) |
| 68 | + const maxWaitTimer = setTimeout(() => { |
| 69 | + setIsCheckingSession(false); |
| 70 | + }, 10000); |
| 71 | + return () => clearTimeout(maxWaitTimer); |
49 | 72 | } |
50 | 73 | } |
51 | 74 |
|
52 | | - checkAuth(); |
53 | | - }, []); |
54 | | - |
55 | | - // Re-check authentication state periodically in case user logs in from another tab |
56 | | - useEffect(() => { |
57 | | - if (!isAuthenticated && !error) { |
58 | | - const interval = setInterval(async () => { |
59 | | - try { |
60 | | - const session = getSession(); |
61 | | - if (session.info.isLoggedIn) { |
62 | | - setIsAuthenticated(true); |
63 | | - setError(null); |
64 | | - } |
65 | | - } catch (err) { |
66 | | - // Silent fail for polling |
67 | | - } |
68 | | - }, 1000); |
| 75 | + |
| 76 | + if (session.isLoggedIn) { |
| 77 | + setIsCheckingSession(false); |
| 78 | + if (isLoginPage) { |
| 79 | + router.replace("/"); |
| 80 | + } |
| 81 | + return; |
| 82 | + } |
69 | 83 |
|
70 | | - return () => clearInterval(interval); |
| 84 | + |
| 85 | + if (wasLoggedIn && !session.isLoggedIn) { |
| 86 | + setIsCheckingSession(false); |
| 87 | + if (!isLoginPage) { |
| 88 | + router.replace("/login"); |
| 89 | + } |
| 90 | + return; |
71 | 91 | } |
72 | | - }, [isAuthenticated, error]); |
73 | | - |
74 | | - const handleRetry = () => { |
75 | | - setError(null); |
76 | | - setIsChecking(true); |
77 | | - setIsAuthenticated(null); |
78 | | - |
79 | | - handleIncomingRedirect({ restorePreviousSession: true }) |
80 | | - .then(() => { |
81 | | - const session = getSession(); |
82 | | - setIsAuthenticated(session.info.isLoggedIn); |
83 | | - }) |
84 | | - .catch((err) => { |
85 | | - const errorMessage = |
86 | | - err instanceof Error ? err : new Error("Authentication check failed"); |
87 | | - setError(errorMessage); |
88 | | - setIsAuthenticated(false); |
89 | | - }) |
90 | | - .finally(() => { |
91 | | - setIsChecking(false); |
92 | | - }); |
93 | | - }; |
94 | | - |
95 | | - if (isChecking) { |
| 92 | + |
| 93 | + // If we have session data (webId, sessionId, etc.) but isLoggedIn is false, |
| 94 | + // the session is likely being restored - wait longer |
| 95 | + // Otherwise, if no session data and no storage indicator, show login quickly |
| 96 | + const shouldWaitForRestore = hasSessionData || hasSessionIndicator; |
| 97 | + const checkTimer = setTimeout(() => { |
| 98 | + setIsCheckingSession(false); |
| 99 | + |
| 100 | + if (!session.isLoggedIn && !isLoginPage && !isOAuthCallback) { |
| 101 | + router.replace("/login"); |
| 102 | + } |
| 103 | + }, shouldWaitForRestore ? 2000 : 200); |
| 104 | + |
| 105 | + return () => clearTimeout(checkTimer); |
| 106 | + }, [session.isLoggedIn, session.webId, session.sessionId, isOAuthCallback, hasSessionIndicator, hasSessionData, wasLoggedIn, isLoginPage, router]); |
| 107 | + |
| 108 | + |
| 109 | + if (isCheckingSession || isOAuthCallback) { |
96 | 110 | return ( |
97 | 111 | <div className="flex min-h-screen items-center justify-center bg-white"> |
98 | 112 | <LoadingSpinner size="md" text="Loading..." /> |
99 | 113 | </div> |
100 | 114 | ); |
101 | 115 | } |
102 | 116 |
|
103 | | - if (error) { |
| 117 | + // If OAuth callback is on login page, we're still processing - show loading |
| 118 | + // This handles the case where OAuth redirects back to /login |
| 119 | + if (isOAuthCallback && isLoginPage) { |
104 | 120 | return ( |
105 | | - <ErrorDisplay |
106 | | - title="Authentication Error" |
107 | | - message={error.message || "Failed to authenticate. Please try again."} |
108 | | - onRetry={handleRetry} |
109 | | - /> |
| 121 | + <div className="flex min-h-screen items-center justify-center bg-white"> |
| 122 | + <LoadingSpinner size="md" text="Loading..." /> |
| 123 | + </div> |
110 | 124 | ); |
111 | 125 | } |
112 | 126 |
|
113 | | - if (!isAuthenticated) { |
114 | | - return <LoginPage />; |
| 127 | + // If not authenticated and not on login page, redirect will happen in useEffect |
| 128 | + // If authenticated and on login page, redirect will happen in useEffect |
| 129 | + // For now, just show children (or nothing if redirecting) |
| 130 | + if (!session.isLoggedIn && !isLoginPage) { |
| 131 | + return null; // Redirecting to login |
115 | 132 | } |
116 | 133 |
|
| 134 | + if (session.isLoggedIn && isLoginPage) { |
| 135 | + return null; // Redirecting to home |
| 136 | + } |
| 137 | + |
| 138 | + // User is authenticated and on correct page, show the app |
117 | 139 | return <>{children}</>; |
118 | 140 | } |
119 | 141 |
|
| 142 | + |
| 143 | +export default function AuthWrapper({ children }: AuthWrapperProps) { |
| 144 | + return ( |
| 145 | + <Suspense |
| 146 | + fallback={ |
| 147 | + <div className="flex min-h-screen items-center justify-center bg-white"> |
| 148 | + <LoadingSpinner size="md" text="Loading..." /> |
| 149 | + </div> |
| 150 | + } |
| 151 | + > |
| 152 | + <AuthWrapperContent>{children}</AuthWrapperContent> |
| 153 | + </Suspense> |
| 154 | + ); |
| 155 | +} |
0 commit comments