Browse Source

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

pull/13907/head
Alejandra 6 months ago
committed by GitHub
parent
commit
496c7090b3
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 22
      frontend/src/main.tsx
  2. 10
      frontend/tests/login.spec.ts

22
frontend/src/main.tsx

@ -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 React from "react"
import React, { StrictMode } from "react"
import ReactDOM from "react-dom/client"
import { routeTree } from "./routeTree.gen"
import { StrictMode } from "react"
import { OpenAPI } from "./client"
import { ApiError, OpenAPI } from "./client"
import { CustomProvider } from "./components/ui/provider"
OpenAPI.BASE = import.meta.env.VITE_API_URL
@ -13,7 +12,20 @@ OpenAPI.TOKEN = async () => {
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 })
declare module "@tanstack/react-router" {

10
frontend/tests/login.spec.ts

@ -115,3 +115,13 @@ test("Logged-out user cannot access protected routes", async ({ page }) => {
await page.goto("/settings")
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")
})
Loading…
Cancel
Save