♻️ Redirect the user to login if we get 401/403 (#1501)

This commit is contained in:
Alejandra
2025-02-19 12:00:08 +00:00
committed by GitHub
parent 50d2a3bfe1
commit 496c7090b3
2 changed files with 27 additions and 5 deletions

View File

@@ -1,11 +1,10 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query" import { MutationCache, QueryCache, QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { RouterProvider, createRouter } from "@tanstack/react-router" import { RouterProvider, createRouter } from "@tanstack/react-router"
import React from "react" import React, { StrictMode } from "react"
import ReactDOM from "react-dom/client" import ReactDOM from "react-dom/client"
import { routeTree } from "./routeTree.gen" import { routeTree } from "./routeTree.gen"
import { StrictMode } from "react" import { ApiError, OpenAPI } from "./client"
import { OpenAPI } from "./client"
import { CustomProvider } from "./components/ui/provider" import { CustomProvider } from "./components/ui/provider"
OpenAPI.BASE = import.meta.env.VITE_API_URL OpenAPI.BASE = import.meta.env.VITE_API_URL
@@ -13,7 +12,20 @@ OpenAPI.TOKEN = async () => {
return localStorage.getItem("access_token") || "" return localStorage.getItem("access_token") || ""
} }
const queryClient = new QueryClient() const handleApiError = (error: Error) => {
if (error instanceof ApiError && [401, 403].includes(error.status)) {
localStorage.removeItem("access_token")
window.location.href = "/login"
}
}
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: handleApiError,
}),
mutationCache: new MutationCache({
onError: handleApiError,
}),
})
const router = createRouter({ routeTree }) const router = createRouter({ routeTree })
declare module "@tanstack/react-router" { declare module "@tanstack/react-router" {

View File

@@ -115,3 +115,13 @@ test("Logged-out user cannot access protected routes", async ({ page }) => {
await page.goto("/settings") await page.goto("/settings")
await page.waitForURL("/login") await page.waitForURL("/login")
}) })
test("Redirects to /login when token is wrong", async ({ page }) => {
await page.goto("/settings")
await page.evaluate(() => {
localStorage.setItem("access_token", "invalid_token")
})
await page.goto("/settings")
await page.waitForURL("/login")
await expect(page).toHaveURL("/login")
})