Skip to content

Commit 496c709

Browse files
authored
♻️ Redirect the user to login if we get 401/403 (#1501)
1 parent 50d2a3b commit 496c709

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

frontend/src/main.tsx

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,31 @@
1-
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
1+
import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query"
22
import { RouterProvider, createRouter } from "@tanstack/react-router"
3-
import React from "react"
3+
import React, { StrictMode } from "react"
44
import ReactDOM from "react-dom/client"
55
import { routeTree } from "./routeTree.gen"
66

7-
import { StrictMode } from "react"
8-
import { OpenAPI } from "./client"
7+
import { ApiError, OpenAPI } from "./client"
98
import { CustomProvider } from "./components/ui/provider"
109

1110
OpenAPI.BASE = import.meta.env.VITE_API_URL
1211
OpenAPI.TOKEN = async () => {
1312
return localStorage.getItem("access_token") || ""
1413
}
1514

16-
const queryClient = new QueryClient()
15+
const handleApiError = (error: Error) => {
16+
if (error instanceof ApiError && [401, 403].includes(error.status)) {
17+
localStorage.removeItem("access_token")
18+
window.location.href = "/login"
19+
}
20+
}
21+
const queryClient = new QueryClient({
22+
queryCache: new QueryCache({
23+
onError: handleApiError,
24+
}),
25+
mutationCache: new MutationCache({
26+
onError: handleApiError,
27+
}),
28+
})
1729

1830
const router = createRouter({ routeTree })
1931
declare module "@tanstack/react-router" {

frontend/tests/login.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,13 @@ test("Logged-out user cannot access protected routes", async ({ page }) => {
115115
await page.goto("/settings")
116116
await page.waitForURL("/login")
117117
})
118+
119+
test("Redirects to /login when token is wrong", async ({ page }) => {
120+
await page.goto("/settings")
121+
await page.evaluate(() => {
122+
localStorage.setItem("access_token", "invalid_token")
123+
})
124+
await page.goto("/settings")
125+
await page.waitForURL("/login")
126+
await expect(page).toHaveURL("/login")
127+
})

0 commit comments

Comments
 (0)