mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-07-04 22:02:16 +02:00
Merge pull request #1545 from AnishSarkar22/fix/auth-session
fix(auth): centralize session refresh retry handling
This commit is contained in:
commit
e6fa9f177e
8 changed files with 99 additions and 96 deletions
|
|
@ -916,7 +916,7 @@ class Config:
|
||||||
|
|
||||||
# JWT Token Lifetimes
|
# JWT Token Lifetimes
|
||||||
ACCESS_TOKEN_LIFETIME_SECONDS = int(
|
ACCESS_TOKEN_LIFETIME_SECONDS = int(
|
||||||
os.getenv("ACCESS_TOKEN_LIFETIME_SECONDS", str(30 * 60)) # 30 minutes
|
os.getenv("ACCESS_TOKEN_LIFETIME_SECONDS", str(60 * 60)) # 60 minutes
|
||||||
)
|
)
|
||||||
MIN_ISSUED_AT = int(os.getenv("MIN_ISSUED_AT", "0"))
|
MIN_ISSUED_AT = int(os.getenv("MIN_ISSUED_AT", "0"))
|
||||||
REFRESH_TOKEN_LIFETIME_SECONDS = int(
|
REFRESH_TOKEN_LIFETIME_SECONDS = int(
|
||||||
|
|
|
||||||
|
|
@ -71,7 +71,7 @@ import { useMessagesSync } from "@/hooks/use-messages-sync";
|
||||||
import { useThreadDetail, useThreadMessages } from "@/hooks/use-thread-queries";
|
import { useThreadDetail, useThreadMessages } from "@/hooks/use-thread-queries";
|
||||||
import { getAgentFilesystemSelection } from "@/lib/agent-filesystem";
|
import { getAgentFilesystemSelection } from "@/lib/agent-filesystem";
|
||||||
import { documentsApiService } from "@/lib/apis/documents-api.service";
|
import { documentsApiService } from "@/lib/apis/documents-api.service";
|
||||||
import { getDesktopAccessToken } from "@/lib/auth-fetch";
|
import { authenticatedFetch } from "@/lib/auth-fetch";
|
||||||
import { type ChatFlow, classifyChatError } from "@/lib/chat/chat-error-classifier";
|
import { type ChatFlow, classifyChatError } from "@/lib/chat/chat-error-classifier";
|
||||||
import { tagPreAcceptSendFailure, toHttpResponseError } from "@/lib/chat/chat-request-errors";
|
import { tagPreAcceptSendFailure, toHttpResponseError } from "@/lib/chat/chat-request-errors";
|
||||||
import { getMentionDocKey } from "@/lib/chat/mention-doc-key";
|
import { getMentionDocKey } from "@/lib/chat/mention-doc-key";
|
||||||
|
|
@ -932,14 +932,11 @@ export default function NewChatPage() {
|
||||||
// Cancel ongoing request
|
// Cancel ongoing request
|
||||||
const cancelRun = useCallback(async () => {
|
const cancelRun = useCallback(async () => {
|
||||||
if (threadId) {
|
if (threadId) {
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await authenticatedFetch(
|
||||||
buildBackendUrl(`/api/v1/threads/${threadId}/cancel-active-turn`),
|
buildBackendUrl(`/api/v1/threads/${threadId}/cancel-active-turn`),
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
|
||||||
credentials: "include",
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
|
@ -986,8 +983,6 @@ export default function NewChatPage() {
|
||||||
|
|
||||||
if (!userQuery.trim() && userImages.length === 0) return;
|
if (!userQuery.trim() && userImages.length === 0) return;
|
||||||
|
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
|
|
||||||
// Lazy thread creation: create thread on first message if it doesn't exist
|
// Lazy thread creation: create thread on first message if it doesn't exist
|
||||||
let currentThreadId = threadId;
|
let currentThreadId = threadId;
|
||||||
let isNewThread = false;
|
let isNewThread = false;
|
||||||
|
|
@ -1159,13 +1154,11 @@ export default function NewChatPage() {
|
||||||
const hasThreadIds = mentionPayload.thread_ids.length > 0;
|
const hasThreadIds = mentionPayload.thread_ids.length > 0;
|
||||||
|
|
||||||
const response = await fetchWithTurnCancellingRetry(() =>
|
const response = await fetchWithTurnCancellingRetry(() =>
|
||||||
fetch(buildBackendUrl("/api/v1/new_chat"), {
|
authenticatedFetch(buildBackendUrl("/api/v1/new_chat"), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
||||||
},
|
},
|
||||||
credentials: "include",
|
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
chat_id: currentThreadId,
|
chat_id: currentThreadId,
|
||||||
user_query: userQuery.trim(),
|
user_query: userQuery.trim(),
|
||||||
|
|
@ -1546,8 +1539,6 @@ export default function NewChatPage() {
|
||||||
stagedDecisionsByInterruptIdRef.current.clear();
|
stagedDecisionsByInterruptIdRef.current.clear();
|
||||||
setIsRunning(true);
|
setIsRunning(true);
|
||||||
|
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
abortControllerRef.current = controller;
|
abortControllerRef.current = controller;
|
||||||
|
|
||||||
|
|
@ -1648,13 +1639,11 @@ export default function NewChatPage() {
|
||||||
localFilesystemEnabled,
|
localFilesystemEnabled,
|
||||||
});
|
});
|
||||||
const response = await fetchWithTurnCancellingRetry(() =>
|
const response = await fetchWithTurnCancellingRetry(() =>
|
||||||
fetch(buildBackendUrl(`/api/v1/threads/${resumeThreadId}/resume`), {
|
authenticatedFetch(buildBackendUrl(`/api/v1/threads/${resumeThreadId}/resume`), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
||||||
},
|
},
|
||||||
credentials: "include",
|
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
search_space_id: searchSpaceId,
|
search_space_id: searchSpaceId,
|
||||||
decisions,
|
decisions,
|
||||||
|
|
@ -1986,8 +1975,6 @@ export default function NewChatPage() {
|
||||||
abortControllerRef.current = null;
|
abortControllerRef.current = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
|
|
||||||
// Extract the original user query BEFORE removing messages (for reload mode)
|
// Extract the original user query BEFORE removing messages (for reload mode)
|
||||||
let userQueryToDisplay: string | undefined;
|
let userQueryToDisplay: string | undefined;
|
||||||
let originalUserMessageContent: ThreadMessageLike["content"] | null = null;
|
let originalUserMessageContent: ThreadMessageLike["content"] | null = null;
|
||||||
|
|
@ -2105,13 +2092,11 @@ export default function NewChatPage() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const response = await fetchWithTurnCancellingRetry(() =>
|
const response = await fetchWithTurnCancellingRetry(() =>
|
||||||
fetch(getRegenerateUrl(threadId), {
|
authenticatedFetch(getRegenerateUrl(threadId), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
||||||
},
|
},
|
||||||
credentials: "include",
|
|
||||||
body: JSON.stringify(requestBody),
|
body: JSON.stringify(requestBody),
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ import {
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useSession } from "@/hooks/use-session";
|
import { useSession } from "@/hooks/use-session";
|
||||||
import { getDesktopAccessToken } from "@/lib/auth-fetch";
|
import { authenticatedFetch, getDesktopAccessToken } from "@/lib/auth-fetch";
|
||||||
import { handleUnauthorized, isPublicRoute, refreshSession } from "@/lib/auth-utils";
|
import { handleUnauthorized, isPublicRoute, refreshSession } from "@/lib/auth-utils";
|
||||||
import { buildBackendUrl } from "@/lib/env-config";
|
import { buildBackendUrl } from "@/lib/env-config";
|
||||||
import type { Context } from "@/types/zero";
|
import type { Context } from "@/types/zero";
|
||||||
|
|
@ -31,26 +31,14 @@ function getCacheURL() {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchZeroContext(isDesktop: boolean): Promise<LoadedZeroContext | null> {
|
async function fetchZeroContext(isDesktop: boolean): Promise<LoadedZeroContext | null> {
|
||||||
const headers: HeadersInit = {};
|
const response = await authenticatedFetch(buildBackendUrl("/zero/context"), {
|
||||||
let desktopAuth: string | undefined;
|
skipAuthRedirect: true,
|
||||||
|
|
||||||
if (isDesktop) {
|
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
if (!token) return null;
|
|
||||||
desktopAuth = token;
|
|
||||||
headers.Authorization = `Bearer ${token}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(buildBackendUrl("/zero/context"), {
|
|
||||||
credentials: "include",
|
|
||||||
headers,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) return null;
|
if (!response.ok) return null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
context: (await response.json()) as ZeroContext,
|
context: (await response.json()) as ZeroContext,
|
||||||
desktopAuth,
|
desktopAuth: isDesktop ? (await getDesktopAccessToken()) || undefined : undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -106,7 +94,7 @@ function ZeroAuthSync({ isDesktop }: { isDesktop: boolean }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isDesktop) {
|
if (isDesktop) {
|
||||||
const newToken = await getDesktopAccessToken();
|
const newToken = await getDesktopAccessToken({ forceRefresh: true });
|
||||||
if (!newToken) {
|
if (!newToken) {
|
||||||
handleUnauthorized();
|
handleUnauthorized();
|
||||||
return;
|
return;
|
||||||
|
|
@ -262,7 +250,7 @@ export function ZeroProvider({ children }: { children: React.ReactNode }) {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const isDesktop = typeof window !== "undefined" && !!window.electronAPI;
|
const isDesktop = typeof window !== "undefined" && !!window.electronAPI;
|
||||||
|
|
||||||
if (!isDesktop && isPublicRoute(pathname)) {
|
if (isPublicRoute(pathname)) {
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ import { z } from "zod";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||||
import { getDesktopAccessToken } from "@/lib/auth-fetch";
|
import { authenticatedFetch } from "@/lib/auth-fetch";
|
||||||
import { buildBackendUrl } from "@/lib/env-config";
|
import { buildBackendUrl } from "@/lib/env-config";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
|
@ -157,14 +157,10 @@ function truncateCommand(command: string, maxLen = 80): string {
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
async function downloadSandboxFile(threadId: string, filePath: string, fileName: string) {
|
async function downloadSandboxFile(threadId: string, filePath: string, fileName: string) {
|
||||||
const token = await getDesktopAccessToken();
|
|
||||||
const url = buildBackendUrl(`/api/v1/threads/${threadId}/sandbox/download`, {
|
const url = buildBackendUrl(`/api/v1/threads/${threadId}/sandbox/download`, {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
});
|
});
|
||||||
const res = await fetch(url, {
|
const res = await authenticatedFetch(url);
|
||||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(`Download failed: ${res.statusText}`);
|
throw new Error(`Download failed: ${res.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { authenticatedFetch } from "@/lib/auth-fetch";
|
||||||
import { buildBackendUrl } from "@/lib/env-config";
|
import { buildBackendUrl } from "@/lib/env-config";
|
||||||
|
|
||||||
type SessionState =
|
type SessionState =
|
||||||
|
|
@ -8,15 +9,6 @@ type SessionState =
|
||||||
| { status: "authenticated"; authenticated: true; accessExpiresAt: number | null }
|
| { status: "authenticated"; authenticated: true; accessExpiresAt: number | null }
|
||||||
| { status: "unauthenticated"; authenticated: false; accessExpiresAt: 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}` } : {};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useSession() {
|
export function useSession() {
|
||||||
const [state, setState] = useState<SessionState>({
|
const [state, setState] = useState<SessionState>({
|
||||||
status: "loading",
|
status: "loading",
|
||||||
|
|
@ -26,9 +18,8 @@ export function useSession() {
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(buildBackendUrl("/auth/session"), {
|
const response = await authenticatedFetch(buildBackendUrl("/auth/session"), {
|
||||||
credentials: "include",
|
skipAuthRedirect: true,
|
||||||
headers: await getSessionHeaders(),
|
|
||||||
});
|
});
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
setState({
|
setState({
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type { ZodType } from "zod";
|
import type { ZodType } from "zod";
|
||||||
|
import { getDesktopAccessToken } from "@/lib/auth-fetch";
|
||||||
import { buildBackendUrl } from "@/lib/env-config";
|
import { buildBackendUrl } from "@/lib/env-config";
|
||||||
import { getClientPlatform } from "../agent-filesystem";
|
import { getClientPlatform } from "../agent-filesystem";
|
||||||
import { handleUnauthorized, refreshSession } from "../auth-utils";
|
import { handleUnauthorized, refreshSession } from "../auth-utils";
|
||||||
|
|
@ -59,11 +60,6 @@ class BaseApiService {
|
||||||
return typeof window !== "undefined" && !!window.electronAPI;
|
return typeof window !== "undefined" && !!window.electronAPI;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getDesktopAccessToken(): Promise<string> {
|
|
||||||
if (!this.isDesktopClient) return "";
|
|
||||||
return (await window.electronAPI?.getAccessToken?.()) || "";
|
|
||||||
}
|
|
||||||
|
|
||||||
async request<T, R extends ResponseType = ResponseType.JSON>(
|
async request<T, R extends ResponseType = ResponseType.JSON>(
|
||||||
url: string,
|
url: string,
|
||||||
responseSchema?: ZodType<T>,
|
responseSchema?: ZodType<T>,
|
||||||
|
|
@ -90,7 +86,7 @@ class BaseApiService {
|
||||||
this.noAuthPrefixes.some((prefix) => url.startsWith(prefix)) ||
|
this.noAuthPrefixes.some((prefix) => url.startsWith(prefix)) ||
|
||||||
/^\/api\/v1\/invites\/[^/]+\/info$/.test(url);
|
/^\/api\/v1\/invites\/[^/]+\/info$/.test(url);
|
||||||
const desktopAccessToken =
|
const desktopAccessToken =
|
||||||
this.isDesktopClient && !isNoAuthEndpoint ? await this.getDesktopAccessToken() : "";
|
this.isDesktopClient && !isNoAuthEndpoint ? (await getDesktopAccessToken()) || "" : "";
|
||||||
const defaultOptions: RequestOptions = {
|
const defaultOptions: RequestOptions = {
|
||||||
headers: {
|
headers: {
|
||||||
...(desktopAccessToken ? { Authorization: `Bearer ${desktopAccessToken}` } : {}),
|
...(desktopAccessToken ? { Authorization: `Bearer ${desktopAccessToken}` } : {}),
|
||||||
|
|
@ -174,7 +170,9 @@ class BaseApiService {
|
||||||
} else if (!isNoAuthEndpoint && !isRefreshRetryBlocked(refreshRetryKey)) {
|
} else if (!isNoAuthEndpoint && !isRefreshRetryBlocked(refreshRetryKey)) {
|
||||||
const refreshed = await refreshSession();
|
const refreshed = await refreshSession();
|
||||||
if (refreshed) {
|
if (refreshed) {
|
||||||
const newToken = this.isDesktopClient ? await this.getDesktopAccessToken() : "";
|
const newToken = this.isDesktopClient
|
||||||
|
? (await getDesktopAccessToken({ forceRefresh: true })) || ""
|
||||||
|
: "";
|
||||||
return this.request(url, responseSchema, {
|
return this.request(url, responseSchema, {
|
||||||
...mergedOptions,
|
...mergedOptions,
|
||||||
headers: {
|
headers: {
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,16 @@ import { handleUnauthorized, isDesktopClient, refreshSession } from "@/lib/auth-
|
||||||
let desktopAccessToken: string | null = null;
|
let desktopAccessToken: string | null = null;
|
||||||
let didSubscribeToDesktopAuth = false;
|
let didSubscribeToDesktopAuth = false;
|
||||||
|
|
||||||
|
type DesktopAccessTokenOptions = {
|
||||||
|
forceRefresh?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AuthenticatedFetchOptions = RequestInit & {
|
||||||
|
skipAuthRedirect?: boolean;
|
||||||
|
skipRefresh?: boolean;
|
||||||
|
forceDesktopTokenRefresh?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
function subscribeToDesktopAuth(): void {
|
function subscribeToDesktopAuth(): void {
|
||||||
if (didSubscribeToDesktopAuth || typeof window === "undefined" || !window.electronAPI) {
|
if (didSubscribeToDesktopAuth || typeof window === "undefined" || !window.electronAPI) {
|
||||||
return;
|
return;
|
||||||
|
|
@ -17,10 +27,12 @@ function subscribeToDesktopAuth(): void {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getDesktopAccessToken(): Promise<string | null> {
|
export async function getDesktopAccessToken(
|
||||||
|
options: DesktopAccessTokenOptions = {}
|
||||||
|
): Promise<string | null> {
|
||||||
if (!isDesktopClient()) return null;
|
if (!isDesktopClient()) return null;
|
||||||
subscribeToDesktopAuth();
|
subscribeToDesktopAuth();
|
||||||
if (desktopAccessToken) return desktopAccessToken;
|
if (desktopAccessToken && !options.forceRefresh) return desktopAccessToken;
|
||||||
const token = (await window.electronAPI?.getAccessToken?.()) || null;
|
const token = (await window.electronAPI?.getAccessToken?.()) || null;
|
||||||
desktopAccessToken = token;
|
desktopAccessToken = token;
|
||||||
return token;
|
return token;
|
||||||
|
|
@ -34,42 +46,61 @@ export function getAuthHeaders(additionalHeaders?: Record<string, string>): Reco
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchWithAuth(
|
||||||
|
url: string,
|
||||||
|
options: RequestInit,
|
||||||
|
{ forceDesktopTokenRefresh = false }: { forceDesktopTokenRefresh?: boolean } = {}
|
||||||
|
): Promise<Response> {
|
||||||
|
const headers = new Headers(options.headers);
|
||||||
|
const token = await getDesktopAccessToken({ forceRefresh: forceDesktopTokenRefresh });
|
||||||
|
if (token) {
|
||||||
|
headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers,
|
||||||
|
credentials: options.credentials ?? "include",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function authenticatedFetch(
|
export async function authenticatedFetch(
|
||||||
url: string,
|
url: string,
|
||||||
options?: RequestInit & { skipAuthRedirect?: boolean; skipRefresh?: boolean }
|
options: AuthenticatedFetchOptions = {}
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const { skipAuthRedirect = false, skipRefresh = false, ...fetchOptions } = options || {};
|
const {
|
||||||
const token = await getDesktopAccessToken();
|
skipAuthRedirect = false,
|
||||||
const headers = {
|
skipRefresh = false,
|
||||||
...(fetchOptions.headers as Record<string, string>),
|
forceDesktopTokenRefresh = false,
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
...fetchOptions
|
||||||
};
|
} = options;
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetchWithAuth(url, fetchOptions, {
|
||||||
...fetchOptions,
|
forceDesktopTokenRefresh,
|
||||||
headers,
|
|
||||||
credentials: "include",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 401 && !skipAuthRedirect) {
|
if (response.status !== 401) {
|
||||||
if (!skipRefresh) {
|
return response;
|
||||||
const refreshed = await refreshSession();
|
}
|
||||||
if (refreshed) {
|
|
||||||
const newToken = await getDesktopAccessToken();
|
|
||||||
return fetch(url, {
|
|
||||||
...fetchOptions,
|
|
||||||
headers: {
|
|
||||||
...(fetchOptions.headers as Record<string, string>),
|
|
||||||
...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),
|
|
||||||
},
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
let unauthorizedResponse = response;
|
||||||
|
if (!skipRefresh) {
|
||||||
|
const refreshed = await refreshSession();
|
||||||
|
if (refreshed) {
|
||||||
|
const retryResponse = await fetchWithAuth(url, fetchOptions, {
|
||||||
|
forceDesktopTokenRefresh: true,
|
||||||
|
});
|
||||||
|
if (retryResponse.status !== 401) {
|
||||||
|
return retryResponse;
|
||||||
|
}
|
||||||
|
unauthorizedResponse = retryResponse;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!skipAuthRedirect) {
|
||||||
handleUnauthorized();
|
handleUnauthorized();
|
||||||
throw new Error("Unauthorized: Redirecting to login page");
|
throw new Error("Unauthorized: Redirecting to login page");
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return unauthorizedResponse;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -188,9 +188,23 @@ async function doRefreshSession(): Promise<boolean> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let refreshPromise: Promise<boolean> | null = null;
|
||||||
|
|
||||||
export async function refreshSession(): Promise<boolean> {
|
export async function refreshSession(): Promise<boolean> {
|
||||||
if (typeof navigator !== "undefined" && "locks" in navigator) {
|
if (refreshPromise) {
|
||||||
return navigator.locks.request("ss-token-refresh", () => doRefreshSession());
|
return refreshPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
refreshPromise = (async () => {
|
||||||
|
if (typeof navigator !== "undefined" && "locks" in navigator) {
|
||||||
|
return navigator.locks.request("ss-token-refresh", () => doRefreshSession());
|
||||||
|
}
|
||||||
|
return doRefreshSession();
|
||||||
|
})();
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await refreshPromise;
|
||||||
|
} finally {
|
||||||
|
refreshPromise = null;
|
||||||
}
|
}
|
||||||
return doRefreshSession();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue