Skip to content

Commit

Permalink
redirecting to homepage when user not logged in (#421)
Browse files Browse the repository at this point in the history
* redirecting to homepage when user not logged in

* linting
  • Loading branch information
AronBuzogany authored May 23, 2024
1 parent aa7383f commit 8b7aae1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const router = createBrowserRouter(
>
<Route index element={<HomePages />} loader={fetchProjectPage} />
<Route path=":lang" element={<LanguagePath />}>
<Route index element={<HomePages />} loader={fetchProjectPage} />
<Route path="home" element={<HomePages />} loader={fetchProjectPage} />
<Route path="courses">
<Route
Expand Down
41 changes: 40 additions & 1 deletion frontend/src/components/Header/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,35 @@
import { Outlet, useLoaderData } from "react-router-dom";
import {
Outlet,
useLoaderData,
useLocation,
useNavigate,
} from "react-router-dom";
import { Header } from "./Header.tsx";
import { Me } from "../../types/me.ts";
import { useEffect } from "react";
import i18next from "i18next";

/**
* Basic layout component that will be used on all routes.
* @returns The Layout component
*/
export default function Layout(): JSX.Element {
const meData: Me = useLoaderData() as Me;
useEnsureLangCodeInPath();
const navigate = useNavigate();
const location = useLocation();

useEffect(() => {
if (
!meData.loggedIn &&
!(
location.pathname === "/" ||
/\/([a-z]{2})?\/home/.test(location.pathname)
)
) {
navigate("/");
}
}, [meData.loggedIn, location.pathname, navigate]);

return (
<>
Expand All @@ -16,3 +38,20 @@ export default function Layout(): JSX.Element {
</>
);
}

const useEnsureLangCodeInPath = () => {
const location = useLocation();
const navigate = useNavigate();

useEffect(() => {
const pathParts = location.pathname.split("/").filter(Boolean);
const langCode = i18next.resolvedLanguage;

// Check if the URL starts with the lang code
if (pathParts[0] !== langCode) {
// Prepend the lang code to the path
const newPath = `/${langCode}/${pathParts.join("/")}`;
navigate(newPath);
}
}, [location, navigate]);
};

0 comments on commit 8b7aae1

Please sign in to comment.