feat(web): add SessionWatcher component for session management and handle session expiration
This commit is contained in:
44
apps/web/components/session-watcher.tsx
Normal file
44
apps/web/components/session-watcher.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { toast } from "@heroui/react";
|
||||
import { useSession, signOut } from "@/lib/auth-client";
|
||||
|
||||
export function SessionWatcher() {
|
||||
const router = useRouter();
|
||||
const { data: session, isPending } = useSession();
|
||||
const wasLoggedIn = useRef(false);
|
||||
const isHandling = useRef(false);
|
||||
|
||||
const handleExpired = useCallback(async () => {
|
||||
if (isHandling.current) return;
|
||||
isHandling.current = true;
|
||||
try {
|
||||
await signOut({ fetchOptions: { credentials: "include" } });
|
||||
} catch {
|
||||
// ignore sign-out errors
|
||||
}
|
||||
toast.warning("登录已过期,请重新登录");
|
||||
router.push("/login");
|
||||
}, [router]);
|
||||
|
||||
// Detect session becoming null after being valid (e.g. server-side expiry)
|
||||
useEffect(() => {
|
||||
if (isPending) return;
|
||||
if (session) {
|
||||
wasLoggedIn.current = true;
|
||||
} else if (wasLoggedIn.current) {
|
||||
handleExpired();
|
||||
}
|
||||
}, [session, isPending, handleExpired]);
|
||||
|
||||
// Detect 401 responses from the API (dispatched by apiFetch)
|
||||
useEffect(() => {
|
||||
const handler = () => handleExpired();
|
||||
window.addEventListener("session:expired", handler);
|
||||
return () => window.removeEventListener("session:expired", handler);
|
||||
}, [handleExpired]);
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user