(frontend) add AuthenticatedView

If an unauthenticated user tries to go to a view requiring
authentication, it should be redirect to the homepage
This commit is contained in:
jbpenrath
2025-04-16 21:53:38 +02:00
committed by Jean-Baptiste PENRATH
parent 35f4174b19
commit 18304a50f9
3 changed files with 37 additions and 12 deletions
+2 -3
View File
@@ -15,7 +15,6 @@ export const login = () => {
interface AuthContextInterface {
user?: User | null;
init?: () => Promise<User | null>;
}
export const AuthContext = React.createContext<AuthContextInterface>({});
@@ -36,7 +35,7 @@ export const Auth = ({
}
}, [query.isError, redirect]);
if (query.isFetched === false) {
if (!query.isFetched) {
return (
<div
style={{
@@ -54,7 +53,7 @@ export const Auth = ({
return (
<AuthContext.Provider
value={{
user: query?.data?.data || null,
user: query.data?.data ?? null,
}}
>
{children}
@@ -0,0 +1,23 @@
import { useAuth } from "@/features/auth/Auth";
import { useRouter } from "next/router";
import { useEffect } from "react";
/**
* Check if a user is authenticated otherwise redirect to the homepage
*/
const AuthenticatedView = ({ children }: { children: React.ReactNode }) => {
const { user } = useAuth();
const router = useRouter();
useEffect(() => {
if (user === null) {
router.replace("/");
}
}, [user, router]);
if (!user) return null;
return children;
};
export default AuthenticatedView;
@@ -3,18 +3,21 @@ import { HeaderRight } from "../header";
import { MailboxPanel } from "@/features/layouts/components/mailbox-panel";
import { PropsWithChildren } from "react";
import { GlobalLayout } from "../global/GlobalLayout";
import AuthenticatedView from "./authenticated-view";
export const MainLayout = ({ children }: PropsWithChildren<{}>) => {
export const MainLayout = ({ children }: PropsWithChildren) => {
return (
<GlobalLayout>
<KitMainLayout
enableResize
leftPanelContent={<MailboxPanel />}
icon={<img src="/images/app-logo.svg" alt="logo" height={32} />}
rightHeaderContent={<HeaderRight />}
>
{children}
</KitMainLayout>
<AuthenticatedView>
<KitMainLayout
enableResize
leftPanelContent={<MailboxPanel />}
icon={<img src="/images/app-logo.svg" alt="logo" height={32} />}
rightHeaderContent={<HeaderRight />}
>
{children}
</KitMainLayout>
</AuthenticatedView>
</GlobalLayout>
)
}