Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions frontend/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,31 @@
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
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" {
Expand Down
10 changes: 10 additions & 0 deletions frontend/tests/login.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})