From 8f74ccf844fc44bd6cc48336992f09d099e06238 Mon Sep 17 00:00:00 2001 From: Guillaume Date: Thu, 30 Nov 2023 11:02:42 +0100 Subject: [PATCH] Disconnect if not authenticated anymore --- pages/app-auth.tsx | 27 +++++++++++++++++++-------- utils/queries.tsx | 15 ++++++++++++--- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/pages/app-auth.tsx b/pages/app-auth.tsx index 7dcad389..b7e93a48 100644 --- a/pages/app-auth.tsx +++ b/pages/app-auth.tsx @@ -14,12 +14,17 @@ const meta = { }; const AppAuth = function () { - const { isAuth, user, isLoading: isAuthLoading, getIdToken } = useAuth(); + const { + isAuth, + user, + isLoading: isAuthLoading, + getIdToken, + logout + } = useAuth(); const router = useRouter(); - const { mutate, isPending, isSuccess, isError, data } = useMutation( - - {mutationFn:async () => { + const { mutate, isPending, isSuccess, isError, data } = useMutation({ + mutationFn: async () => { return fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}/auth/token`, { method: 'GET', headers: { @@ -30,14 +35,20 @@ const AppAuth = function () { return res.json(); } + if (res.status === 401) { + logout(); + router.push('/login/'); + + return; + } + throw new Error(); }); }, - onSuccess: (data) => { - window.location.assign(`mockoon://auth?token=${data.token}`); - } + onSuccess: (data) => { + window.location.assign(`mockoon://auth?token=${data.token}`); } - ); + }); useEffect(() => { if (!isAuthLoading) { diff --git a/utils/queries.tsx b/utils/queries.tsx index da55ecbd..977f9ec9 100644 --- a/utils/queries.tsx +++ b/utils/queries.tsx @@ -1,16 +1,18 @@ import { useQuery } from '@tanstack/react-query'; +import { useRouter } from 'next/router'; import { Plans, Team, User } from '../models/user.model'; import { useAuth } from './auth'; const useCurrentUser = () => { - const auth = useAuth(); + const { getIdToken, isAuth, logout } = useAuth(); + const router = useRouter(); const { isLoading, error, data, isFetching } = useQuery({ queryKey: ['currentUser'], - enabled: auth.isAuth, + enabled: isAuth, refetchOnMount: false, queryFn: async () => { - const token = await auth.getIdToken(); + const token = await getIdToken(); if (!token) { return null; @@ -25,6 +27,13 @@ const useCurrentUser = () => { return res.json(); } + if (res.status === 401) { + logout(); + router.push('/login/'); + + return; + } + throw new Error(); }); },