mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-06-26 21:39:43 +02:00
refactor(auth): streamline session handling with authenticatedFetch
This commit is contained in:
parent
4b6bcaeb1b
commit
3ce759f1d6
2 changed files with 56 additions and 51 deletions
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { refreshSession } from "@/lib/auth-utils";
|
||||
import { authenticatedFetch } from "@/lib/auth-fetch";
|
||||
import { buildBackendUrl } from "@/lib/env-config";
|
||||
|
||||
type SessionState =
|
||||
|
|
@ -9,22 +9,6 @@ type SessionState =
|
|||
| { status: "authenticated"; authenticated: true; accessExpiresAt: number | null }
|
||||
| { status: "unauthenticated"; authenticated: false; accessExpiresAt: null };
|
||||
|
||||
async function getSessionHeaders(): Promise<HeadersInit> {
|
||||
if (typeof window === "undefined" || !window.electronAPI?.getAccessToken) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const token = await window.electronAPI.getAccessToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
async function fetchSession(): Promise<Response> {
|
||||
return fetch(buildBackendUrl("/auth/session"), {
|
||||
credentials: "include",
|
||||
headers: await getSessionHeaders(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
const [state, setState] = useState<SessionState>({
|
||||
status: "loading",
|
||||
|
|
@ -34,13 +18,9 @@ export function useSession() {
|
|||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
let response = await fetchSession();
|
||||
if (response.status === 401) {
|
||||
const refreshed = await refreshSession();
|
||||
if (refreshed) {
|
||||
response = await fetchSession();
|
||||
}
|
||||
}
|
||||
const response = await authenticatedFetch(buildBackendUrl("/auth/session"), {
|
||||
skipAuthRedirect: true,
|
||||
});
|
||||
if (!response.ok) {
|
||||
setState({
|
||||
status: "unauthenticated",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue