|
| 1 | +import axios from "axios" |
1 | 2 | import { useAuth } from "components/AuthProvider/AuthProvider"
|
2 |
| -import { FC } from "react" |
| 3 | +import { FC, useEffect } from "react" |
3 | 4 | import { Outlet, Navigate, useLocation } from "react-router-dom"
|
4 | 5 | import { embedRedirect } from "../../utils/redirect"
|
5 | 6 | import { FullScreenLoader } from "../Loader/FullScreenLoader"
|
6 | 7 | import { DashboardProvider } from "components/Dashboard/DashboardProvider"
|
7 | 8 | import { ProxyProvider } from "contexts/ProxyContext"
|
8 | 9 |
|
9 | 10 | export const RequireAuth: FC = () => {
|
10 |
| - const [authState] = useAuth() |
| 11 | + const [authState, authSend] = useAuth() |
11 | 12 | const location = useLocation()
|
12 | 13 | const isHomePage = location.pathname === "/"
|
13 | 14 | const navigateTo = isHomePage
|
14 | 15 | ? "/login"
|
15 | 16 | : embedRedirect(`${location.pathname}${location.search}`)
|
16 | 17 |
|
| 18 | + useEffect(() => { |
| 19 | + const interceptorHandle = axios.interceptors.response.use( |
| 20 | + (okResponse) => okResponse, |
| 21 | + (error) => { |
| 22 | + // 401 Unauthorized |
| 23 | + // If we encountered an authentication error, then our token is probably |
| 24 | + // invalid and we should update the auth state to reflect that. |
| 25 | + if (error.response.status === 401) { |
| 26 | + authSend("SIGN_OUT") |
| 27 | + } |
| 28 | + |
| 29 | + // Otherwise, pass the response through so that it can be displayed in the UI |
| 30 | + return Promise.reject(error) |
| 31 | + }, |
| 32 | + ) |
| 33 | + |
| 34 | + return () => { |
| 35 | + axios.interceptors.response.eject(interceptorHandle) |
| 36 | + } |
| 37 | + }, []) |
| 38 | + |
17 | 39 | if (authState.matches("signedOut")) {
|
18 | 40 | return <Navigate to={navigateTo} state={{ isRedirect: !isHomePage }} />
|
19 | 41 | } else if (authState.matches("configuringTheFirstUser")) {
|
|
0 commit comments