From a46f06fe64eb6e7491dabd8f57eeefa5a39ecbae Mon Sep 17 00:00:00 2001 From: Matej Kubinec Date: Thu, 4 Jul 2024 16:18:49 +0200 Subject: [PATCH] PMM-11231 Rework redirect to login --- ui/src/components/main/Main.tsx | 28 ++++++++++++++------------ ui/src/constants.ts | 1 + ui/src/contexts/auth/auth.provider.tsx | 15 +++++++------- ui/src/contexts/auth/auth.utils.ts | 4 +++- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/ui/src/components/main/Main.tsx b/ui/src/components/main/Main.tsx index 96e03049dd..1fcbe5f50e 100644 --- a/ui/src/components/main/Main.tsx +++ b/ui/src/components/main/Main.tsx @@ -6,22 +6,24 @@ import { useAuth } from 'contexts/auth'; export const Main = () => { const { isLoading } = useAuth(); + if (isLoading) { + return ( + + + + ); + } + return ( - {isLoading ? ( - - - - ) : ( - - )} + ); }; diff --git a/ui/src/constants.ts b/ui/src/constants.ts index c571961e53..a104b3f9f0 100644 --- a/ui/src/constants.ts +++ b/ui/src/constants.ts @@ -1 +1,2 @@ export const PMM_HOME_URL = '/graph/d/pmm-home'; +export const PMM_LOGIN_URL = '/graph/login'; diff --git a/ui/src/contexts/auth/auth.provider.tsx b/ui/src/contexts/auth/auth.provider.tsx index be86801383..d2bc9c165b 100644 --- a/ui/src/contexts/auth/auth.provider.tsx +++ b/ui/src/contexts/auth/auth.provider.tsx @@ -1,4 +1,4 @@ -import { FC, PropsWithChildren, useEffect } from 'react'; +import { FC, PropsWithChildren, useMemo } from 'react'; import { AuthContext } from './auth.context'; import { useQuery } from '@tanstack/react-query'; import { rotateToken } from 'api/auth'; @@ -13,15 +13,16 @@ export const AuthProvider: FC = ({ children }) => { refetchIntervalInBackground: true, retry: false, }); - - useEffect(() => { + const shouldRedirectToLogin = useMemo(() => { const response = (error as AxiosError)?.response; - - if (response?.status === HttpStatusCode.Unauthorized) { - redirectToLogin(); - } + return response?.status === HttpStatusCode.Unauthorized; }, [error]); + if (shouldRedirectToLogin) { + redirectToLogin(); + return null; + } + return ( {children} diff --git a/ui/src/contexts/auth/auth.utils.ts b/ui/src/contexts/auth/auth.utils.ts index 360cb0f807..e586b64ffa 100644 --- a/ui/src/contexts/auth/auth.utils.ts +++ b/ui/src/contexts/auth/auth.utils.ts @@ -1,3 +1,5 @@ +import { PMM_LOGIN_URL } from 'constants'; + export const getSessionExpiry = () => { const expiryCookie = getSessionExpiryCookie(); @@ -33,5 +35,5 @@ export const getSessionExpiryCookie = () => .find((row) => row.startsWith('grafana_session_expiry=')); export const redirectToLogin = () => { - window.location.replace('/graph/login'); + window.location.replace(PMM_LOGIN_URL); };