From 19813ae75782c3868086d0f025a7cbafac5bd2b2 Mon Sep 17 00:00:00 2001 From: ledouxm Date: Thu, 12 Dec 2024 15:47:15 +0100 Subject: [PATCH] hotfix: refresh token --- packages/frontend/src/api.ts | 5 +++-- packages/frontend/src/db/Connector.ts | 8 +++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/frontend/src/api.ts b/packages/frontend/src/api.ts index 1449857..a9f19cf 100644 --- a/packages/frontend/src/api.ts +++ b/packages/frontend/src/api.ts @@ -7,12 +7,12 @@ import { getTokenOrRefresh } from "./db/Connector"; export const apiStore = createStore("auth", "access"); -export const createApiClientWithUrl = (url: string) => { +export const createApiClientWithUrl = (url: string, ignoreToken?: boolean) => { return createApiClient(async (method, url, parameters) => { const { body, query, header } = parameters || {}; let token; - if (ref.token) { + if (!ignoreToken && ref.token) { token = await getTokenOrRefresh(); } @@ -26,6 +26,7 @@ export const createApiClientWithUrl = (url: string) => { }; export const api = createApiClientWithUrl(ENV.VITE_BACKEND_URL); +export const unauthenticatedApi = createApiClientWithUrl(ENV.VITE_BACKEND_URL, true); set("url", ENV.VITE_BACKEND_URL, apiStore); const ref = { token: null as string | null, diff --git a/packages/frontend/src/db/Connector.ts b/packages/frontend/src/db/Connector.ts index 69dabc7..e14b6f7 100644 --- a/packages/frontend/src/db/Connector.ts +++ b/packages/frontend/src/db/Connector.ts @@ -1,6 +1,6 @@ import { UpdateType, PowerSyncBackendConnector, AbstractPowerSyncDatabase, CrudBatch } from "@powersync/web"; import { safeJSONParse } from "pastable"; -import { api } from "../api"; +import { api, unauthenticatedApi } from "../api"; import { get } from "idb-keyval"; import { getPicturesStore } from "../features/idb"; import { ENV } from "../envVars"; @@ -54,11 +54,11 @@ export class Connector implements PowerSyncBackendConnector { } export const getTokenOrRefresh = async () => { - const authData = safeJSONParse(window.localStorage.getItem("crvif/auth") ?? ""); + let authData = safeJSONParse(window.localStorage.getItem("crvif/auth") ?? ""); if (!authData) throw new Error("No auth data found"); if (new Date(authData.expiresAt) < new Date()) { - const resp = await api.get("/api/refresh-token", { + const resp = await unauthenticatedApi.get("/api/refresh-token", { query: { token: authData.token, refreshToken: authData.refreshToken! }, }); @@ -69,6 +69,8 @@ export const getTokenOrRefresh = async () => { console.log("token refreshed"); window.localStorage.setItem("crvif/auth", JSON.stringify({ ...authData, ...resp })); } + + authData = safeJSONParse(window.localStorage.getItem("crvif/auth") ?? ""); } return authData.token as string;