ultisuite-client/lib/auth/handle-unauthorized.ts
R3D347HR4Y 5304790ed5
Some checks are pending
E2E / Playwright e2e (push) Waiting to run
feat(auth): enhance session management and identity provider settings
- Added SessionGuard component to manage session expiration and online status.
- Updated AuthProvider to streamline session fetching and handling.
- Introduced IdentityProvidersSection for managing OAuth, SAML, and LDAP identity providers.
- Implemented identity provider guides for easier configuration.
- Enhanced mail settings with infinite scroll option for improved user experience.
- Updated global styles and layout components for better consistency across the application.
2026-06-09 09:36:46 +02:00

80 lines
1.8 KiB
TypeScript

import { useAuthStore } from "@/lib/api/auth-store"
import { ensureAccessToken } from "@/lib/auth/ensure-access-token"
import { fetchSession, tryRefreshSession } from "@/lib/auth/session-sync"
import {
isSessionExpired,
useSessionGuardStore,
} from "@/lib/auth/session-guard-store"
export type UnauthorizedResolution = "refreshed" | "offline" | "expired"
type HandleUnauthorizedOptions = {
/** API still returns 401 after a session refresh attempt. */
forceExpired?: boolean
}
let pending: Promise<UnauthorizedResolution> | null = null
function isBrowserOffline() {
return typeof navigator !== "undefined" && !navigator.onLine
}
function markSessionExpired() {
useAuthStore.getState().logout()
useSessionGuardStore.getState().setExpired()
}
async function resolveUnauthorized(
opts?: HandleUnauthorizedOptions
): Promise<UnauthorizedResolution> {
if (isSessionExpired()) {
return "expired"
}
if (opts?.forceExpired) {
markSessionExpired()
return "expired"
}
if (isBrowserOffline()) {
useSessionGuardStore.getState().setOffline()
return "offline"
}
if (await tryRefreshSession()) {
return "refreshed"
}
const session = await fetchSession()
if (session?.authenticated) {
return "refreshed"
}
if (await ensureAccessToken()) {
return "refreshed"
}
markSessionExpired()
return "expired"
}
/** Verify session after a 401; deduped across concurrent API calls. */
export function handleUnauthorized(
opts?: HandleUnauthorizedOptions
): Promise<UnauthorizedResolution> {
if (isSessionExpired()) {
return Promise.resolve("expired")
}
if (opts?.forceExpired) {
return resolveUnauthorized(opts)
}
if (!pending) {
pending = resolveUnauthorized().finally(() => {
pending = null
})
}
return pending
}