ultisuite-client/lib/auth/ensure-access-token.ts
R3D347HR4Y d6d18f911b
Some checks failed
E2E / Playwright e2e (push) Has been cancelled
Lots of stuff and mobile app
2026-06-17 00:13:28 +02:00

31 lines
986 B
TypeScript

import { useAuthStore } from "@/lib/api/auth-store"
import { fetchSession, applySessionToStore } from "@/lib/auth/session-sync"
import { useNativeRuntime } from "@/lib/platform"
import { ensureNativeAccessToken } from "@/lib/auth/native-session"
let syncPromise: Promise<string | null> | null = null
/**
* Resolve the current bearer token.
* - Web: from the httpOnly session cookies (via `/api/auth/session`).
* - Native (Tauri): from the OS secure store, refreshing against Authentik.
*/
export async function ensureAccessToken(): Promise<string | null> {
if (!syncPromise) {
syncPromise = (async () => {
if (useNativeRuntime()) {
return ensureNativeAccessToken()
}
const data = await fetchSession()
if (data && applySessionToStore(data)) {
return useAuthStore.getState().accessToken
}
useAuthStore.getState().logout()
return null
})().finally(() => {
syncPromise = null
})
}
return syncPromise
}