mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-06-26 21:39:43 +02:00
fix(web):centralize session api handling
This commit is contained in:
parent
fcf2485863
commit
411bb0019e
2 changed files with 98 additions and 6 deletions
54
surfsense_web/hooks/use-session.ts
Normal file
54
surfsense_web/hooks/use-session.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { buildBackendUrl } from "@/lib/env-config";
|
||||
|
||||
type SessionState =
|
||||
| { status: "loading"; authenticated: false; accessExpiresAt: null }
|
||||
| { status: "authenticated"; authenticated: true; accessExpiresAt: number }
|
||||
| { status: "unauthenticated"; authenticated: false; accessExpiresAt: null };
|
||||
|
||||
export function useSession() {
|
||||
const [state, setState] = useState<SessionState>({
|
||||
status: "loading",
|
||||
authenticated: false,
|
||||
accessExpiresAt: null,
|
||||
});
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(buildBackendUrl("/auth/session"), {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
setState({
|
||||
status: "unauthenticated",
|
||||
authenticated: false,
|
||||
accessExpiresAt: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const data = (await response.json()) as {
|
||||
authenticated: boolean;
|
||||
access_expires_at: number;
|
||||
};
|
||||
setState({
|
||||
status: "authenticated",
|
||||
authenticated: true,
|
||||
accessExpiresAt: data.access_expires_at,
|
||||
});
|
||||
} catch {
|
||||
setState({
|
||||
status: "unauthenticated",
|
||||
authenticated: false,
|
||||
accessExpiresAt: null,
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { ...state, refresh };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue