Skip to content

Commit

Permalink
Disconnect if not authenticated anymore
Browse files Browse the repository at this point in the history
  • Loading branch information
255kb committed Nov 30, 2023
1 parent de19d34 commit 8f74ccf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
27 changes: 19 additions & 8 deletions pages/app-auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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) {
Expand Down
15 changes: 12 additions & 3 deletions utils/queries.tsx
Original file line number Diff line number Diff line change
@@ -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<User>({
queryKey: ['currentUser'],
enabled: auth.isAuth,
enabled: isAuth,
refetchOnMount: false,
queryFn: async () => {
const token = await auth.getIdToken();
const token = await getIdToken();

if (!token) {
return null;
Expand All @@ -25,6 +27,13 @@ const useCurrentUser = () => {
return res.json();
}

if (res.status === 401) {
logout();
router.push('/login/');

return;
}

throw new Error();
});
},
Expand Down

0 comments on commit 8f74ccf

Please sign in to comment.