Unverified Commit 3010f10e authored by Peter Etelej's avatar Peter Etelej Committed by GitHub

fix: access token refresh on web app (#5681)

parent 334dfef7
import { timestampDate } from "@bufbuild/protobuf/wkt"; import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Code, ConnectError, createClient, type Interceptor } from "@connectrpc/connect"; import { Code, ConnectError, createClient, type Interceptor } from "@connectrpc/connect";
import { createConnectTransport } from "@connectrpc/connect-web"; import { createConnectTransport } from "@connectrpc/connect-web";
import { getAccessToken, isTokenExpired, REQUEST_TOKEN_EXPIRY_BUFFER_MS, setAccessToken } from "./auth-state"; import { getAccessToken, hasStoredToken, isTokenExpired, REQUEST_TOKEN_EXPIRY_BUFFER_MS, setAccessToken } from "./auth-state";
import { ActivityService } from "./types/proto/api/v1/activity_service_pb"; import { ActivityService } from "./types/proto/api/v1/activity_service_pb";
import { AttachmentService } from "./types/proto/api/v1/attachment_service_pb"; import { AttachmentService } from "./types/proto/api/v1/attachment_service_pb";
import { AuthService } from "./types/proto/api/v1/auth_service_pb"; import { AuthService } from "./types/proto/api/v1/auth_service_pb";
...@@ -124,7 +124,13 @@ async function refreshAndGetAccessToken(): Promise<string> { ...@@ -124,7 +124,13 @@ async function refreshAndGetAccessToken(): Promise<string> {
async function getRequestToken(): Promise<string | null> { async function getRequestToken(): Promise<string | null> {
let token = getAccessToken(); let token = getAccessToken();
if (!token) { if (!token) {
return null; if (!hasStoredToken()) return null;
try {
token = await refreshAndGetAccessToken();
} catch {
return null;
}
return token;
} }
// Preflight refresh: avoid sending requests with expired access tokens. // Preflight refresh: avoid sending requests with expired access tokens.
......
import { useEffect } from "react"; import { useEffect } from "react";
import { FOCUS_TOKEN_EXPIRY_BUFFER_MS, getAccessToken, isTokenExpired } from "@/auth-state"; import { FOCUS_TOKEN_EXPIRY_BUFFER_MS, hasStoredToken, isTokenExpired } from "@/auth-state";
/** /**
* Hook that proactively refreshes the access token when the tab becomes visible * Hook that proactively refreshes the access token when the tab becomes visible
...@@ -20,9 +20,8 @@ export function useTokenRefreshOnFocus(refreshFn: () => Promise<void>, enabled: ...@@ -20,9 +20,8 @@ export function useTokenRefreshOnFocus(refreshFn: () => Promise<void>, enabled:
return; return;
} }
// Only refresh if we have a token // Only refresh if the user has logged in before (token in localStorage)
const token = getAccessToken(); if (!hasStoredToken()) {
if (!token) {
return; return;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment