fix: auth post (#626)

Co-authored-by: Igor Loskutov <igor.loskutoff@gmail.com>
This commit is contained in:
Igor Monadical
2025-09-09 16:27:46 -04:00
committed by GitHub
parent cde99ca271
commit 3b85ff3bdf
2 changed files with 23 additions and 4 deletions

View File

@@ -88,6 +88,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}; };
// not useEffect, we need it ASAP // not useEffect, we need it ASAP
// apparently, still no guarantee this code runs before mutations are fired
configureApiAuth( configureApiAuth(
contextValue.status === "authenticated" ? contextValue.accessToken : null, contextValue.status === "authenticated" ? contextValue.accessToken : null,
); );

View File

@@ -14,9 +14,27 @@ export const client = createClient<paths>({
baseUrl: API_URL, baseUrl: API_URL,
}); });
// has to be called BEFORE $api is created with createFetchClient<paths>(client) or onRequest doesn't fire [at least for POST] const waitForAuthTokenDefinitivePresenceOrAbscence = async () => {
let tries = 0;
let time = 0;
const STEP = 100;
while (currentAuthToken === undefined) {
await new Promise((resolve) => setTimeout(resolve, STEP));
time += STEP;
tries++;
// most likely first try is more than enough, if it's more there's already something weird happens
if (tries > 10) {
// even when there's no auth assumed at all, we probably should explicitly call configureApiAuth(null)
throw new Error(
`Could not get auth token definitive presence/absence in ${time}ms. not calling configureApiAuth?`,
);
}
}
};
client.use({ client.use({
onRequest({ request }) { async onRequest({ request }) {
await waitForAuthTokenDefinitivePresenceOrAbscence();
if (currentAuthToken) { if (currentAuthToken) {
request.headers.set("Authorization", `Bearer ${currentAuthToken}`); request.headers.set("Authorization", `Bearer ${currentAuthToken}`);
} }
@@ -35,9 +53,9 @@ client.use({
export const $api = createFetchClient<paths>(client); export const $api = createFetchClient<paths>(client);
let currentAuthToken: string | null | undefined = null; let currentAuthToken: string | null | undefined = undefined;
// the function contract: lightweight, idempotent // the function contract: lightweight, idempotent
export const configureApiAuth = (token: string | null | undefined) => { export const configureApiAuth = (token: string | null) => {
currentAuthToken = token; currentAuthToken = token;
}; };