mirror of
https://github.com/Monadical-SAS/reflector.git
synced 2025-12-20 12:19:06 +00:00
fix: auth post (#626)
Co-authored-by: Igor Loskutov <igor.loskutoff@gmail.com>
This commit is contained in:
@@ -88,6 +88,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
};
|
||||
|
||||
// not useEffect, we need it ASAP
|
||||
// apparently, still no guarantee this code runs before mutations are fired
|
||||
configureApiAuth(
|
||||
contextValue.status === "authenticated" ? contextValue.accessToken : null,
|
||||
);
|
||||
|
||||
@@ -14,9 +14,27 @@ export const client = createClient<paths>({
|
||||
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({
|
||||
onRequest({ request }) {
|
||||
async onRequest({ request }) {
|
||||
await waitForAuthTokenDefinitivePresenceOrAbscence();
|
||||
if (currentAuthToken) {
|
||||
request.headers.set("Authorization", `Bearer ${currentAuthToken}`);
|
||||
}
|
||||
@@ -35,9 +53,9 @@ client.use({
|
||||
|
||||
export const $api = createFetchClient<paths>(client);
|
||||
|
||||
let currentAuthToken: string | null | undefined = null;
|
||||
let currentAuthToken: string | null | undefined = undefined;
|
||||
|
||||
// the function contract: lightweight, idempotent
|
||||
export const configureApiAuth = (token: string | null | undefined) => {
|
||||
export const configureApiAuth = (token: string | null) => {
|
||||
currentAuthToken = token;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user