Skip to content

Commit

Permalink
hotfix: refresh token
Browse files Browse the repository at this point in the history
  • Loading branch information
ledouxm committed Dec 12, 2024
1 parent 2a1674f commit 19813ae
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
5 changes: 3 additions & 2 deletions packages/frontend/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand All @@ -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,
Expand Down
8 changes: 5 additions & 3 deletions packages/frontend/src/db/Connector.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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! },
});

Expand All @@ -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;
Expand Down

0 comments on commit 19813ae

Please sign in to comment.