feat(ui): added new auth guard with react-query and axios

This commit is contained in:
akhilmhdh
2023-01-26 00:14:01 +05:30
parent a6f480d3f8
commit a6387e7552
16 changed files with 234 additions and 30 deletions
@@ -0,0 +1,49 @@
import { ReactNode, useEffect } from 'react';
import { useRouter } from 'next/router';
import { publicPaths } from '@app/const';
import { useToggle } from '@app/hooks';
import { useGetAuthToken } from '@app/hooks/api';
import { isLoggedIn } from '@app/reactQuery';
type Props = {
children: ReactNode;
};
// TODO(akhilmhdh): Using react-simple-animate from hard dom offloading
// smoother dom offloading needs to be done
// Authentication controller
// Does route checking
// Provide a context for whole app to notify user is authorized or not
export const AuthProvider = ({ children }: Props): JSX.Element => {
const { isLoading } = useGetAuthToken();
const { pathname, push } = useRouter();
const [isReady, setIsReady] = useToggle(false);
useEffect(() => {
// check if loading of auth is done
if (!isLoading) {
// not a public path and not authenticated kick to login page
if (!publicPaths.includes(pathname) && !isLoggedIn()) {
push('/login').then(() => {
setIsReady.on();
});
} else {
// else good to go
setIsReady.on();
}
}
}, [pathname, isLoading]);
// wait for app to load the auth state
if (isLoading || !isReady) {
return (
<div className="flex items-center justify-center w-screen h-screen bg-bunker-800">
<img src="/images/loading/loading.gif" alt="loading animation" className="w-80" />
</div>
);
}
return children as JSX.Element;
};
@@ -0,0 +1 @@
export { AuthProvider } from './AuthContext';