diff --git a/src/common/util/useCurrentPerson.ts b/src/common/util/useCurrentPerson.ts index 691c8cab4..a68bb231c 100644 --- a/src/common/util/useCurrentPerson.ts +++ b/src/common/util/useCurrentPerson.ts @@ -1,6 +1,6 @@ -import { AxiosResponse } from 'axios' +import { AxiosError, AxiosResponse } from 'axios' import { useQuery } from '@tanstack/react-query' -import { useSession } from 'next-auth/react' +import { signOut, useSession } from 'next-auth/react' import { apiClient } from 'service/apiClient' import { endpoints } from 'service/apiEndpoints' @@ -15,20 +15,45 @@ type CurrentPerson = { status: 'unauthenticated' } +//Note: Used only for /profile page export function getCurrentPerson(isNew = false) { const { data: session } = useSession() - return useQuery( + const query = useQuery( [isNew ? endpoints.account.new.url : endpoints.account.me.url], authQueryFnFactory(session?.accessToken), + { + retry: (count, err) => { + if (err.isAxiosError && err.response?.status === 401) { + return false + } + return true + }, + }, ) + if (query.error && query.error.response?.status === 401) + signOut({ redirect: true, callbackUrl: '/login' }) + + return query } +//Note: Used for every other page export function useCurrentPerson() { const { data: session } = useSession() - return useQuery( + const query = useQuery( [endpoints.account.me.url], authQueryFnFactory(session?.accessToken), + { + retry: (count, err) => { + if (err.isAxiosError && err.response?.status === 401) { + return false + } + return true + }, + }, ) + if (query.error && query.error.response?.status === 401) signOut({ redirect: false }) + + return query } export function updateCurrentPerson() { diff --git a/src/components/client/auth/profile/ProfilePage.tsx b/src/components/client/auth/profile/ProfilePage.tsx index 264c0ce1e..a53bc3e28 100644 --- a/src/components/client/auth/profile/ProfilePage.tsx +++ b/src/components/client/auth/profile/ProfilePage.tsx @@ -19,6 +19,7 @@ import { routes } from 'common/routes' import Layout from 'components/client/layout/Layout' import { ProfileTabs, ProfileTab, tabs } from './tabs' +import { getCurrentPerson } from 'common/util/useCurrentPerson' const PREFIX = 'ProfilePage' @@ -50,6 +51,9 @@ export default function ProfilePage() { const router = useRouter() const matches = useMediaQuery(theme.breakpoints.down('sm')) const currentTab = router.query.slug ?? ProfileTabs.donations + + const { error: userError, isError } = getCurrentPerson(!!router.query?.register) + const tab = useMemo(() => { return tabs.find((tab) => tab.slug === currentTab) ?? tabs[0] }, [currentTab]) @@ -62,6 +66,14 @@ export default function ProfilePage() { return Not authenticated } + if (isError && userError.response && userError.response.status === 401) { + return ( + + The user session has expired. Redirecting to login page + + ) + } + const { Component: SelectedTab } = tab return (