From 67e96d52020380a5d1ff5f970a96467f3188c838 Mon Sep 17 00:00:00 2001 From: Kirill Zhdanov Date: Sat, 16 Nov 2024 15:18:41 +0700 Subject: [PATCH] fix: #400 logout because token expired or corrupted --- frontend/src/hooks/useAuth.ts | 6 ++++-- frontend/src/routes/_layout.tsx | 10 +++++++++- frontend/src/routes/login.tsx | 8 ++++---- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/frontend/src/hooks/useAuth.ts b/frontend/src/hooks/useAuth.ts index 76b0abdfd3..44db632e1c 100644 --- a/frontend/src/hooks/useAuth.ts +++ b/frontend/src/hooks/useAuth.ts @@ -18,11 +18,11 @@ const isLoggedIn = () => { } const useAuth = () => { - const [error, setError] = useState(null) + const [errorSetter, setError] = useState(null) const navigate = useNavigate() const showToast = useCustomToast() const queryClient = useQueryClient() - const { data: user, isLoading } = useQuery({ + const { data: user, isLoading, error, errorUpdateCount } = useQuery({ queryKey: ["currentUser"], queryFn: UsersService.readUserMe, enabled: isLoggedIn(), @@ -92,7 +92,9 @@ const useAuth = () => { logout, user, isLoading, + errorSetter, error, + errorUpdateCount, resetError: () => setError(null), } } diff --git a/frontend/src/routes/_layout.tsx b/frontend/src/routes/_layout.tsx index 9a6cfa3b81..2c3aeacfd6 100644 --- a/frontend/src/routes/_layout.tsx +++ b/frontend/src/routes/_layout.tsx @@ -1,3 +1,5 @@ +import { useEffect } from 'react' + import { Flex, Spinner } from "@chakra-ui/react" import { Outlet, createFileRoute, redirect } from "@tanstack/react-router" @@ -17,7 +19,13 @@ export const Route = createFileRoute("/_layout")({ }) function Layout() { - const { isLoading } = useAuth() + const { isLoading, error, errorUpdateCount, logout } = useAuth() + useEffect(() => { + if (errorUpdateCount && error?.message === "Forbidden") { + console.log("____Unauth____logout"); + logout(); + } + }, [errorUpdateCount, error, logout]); return ( diff --git a/frontend/src/routes/login.tsx b/frontend/src/routes/login.tsx index 20a9be6564..bc00ae59bb 100644 --- a/frontend/src/routes/login.tsx +++ b/frontend/src/routes/login.tsx @@ -38,7 +38,7 @@ export const Route = createFileRoute("/login")({ function Login() { const [show, setShow] = useBoolean() - const { loginMutation, error, resetError } = useAuth() + const { loginMutation, errorSetter, resetError } = useAuth() const { register, handleSubmit, @@ -84,7 +84,7 @@ function Login() { alignSelf="center" mb={4} /> - + {errors.username.message} )} - + - {error && {error}} + {errorSetter && {errorSetter}} Forgot password?