♻️ Use middleware for protecting routes (#1010)

This commit is contained in:
Luke Vella 2024-01-31 14:32:51 +07:00 committed by GitHub
parent 9d75e5112a
commit 47dd3a0ff2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 27 deletions

View file

@ -2,30 +2,11 @@ import { cn } from "@rallly/ui";
import { Button } from "@rallly/ui/button";
import { MenuIcon } from "lucide-react";
import Link from "next/link";
import { signIn, useSession } from "next-auth/react";
import React from "react";
import { Sidebar } from "@/app/[locale]/(admin)/sidebar";
import { LogoLink } from "@/app/components/logo-link";
import { CurrentUserAvatar } from "@/components/user";
import { isSelfHosted } from "@/utils/constants";
const Auth = ({ children }: { children: React.ReactNode }) => {
const session = useSession();
const isAuthenticated = !!session.data?.user.email;
React.useEffect(() => {
if (!isAuthenticated) {
signIn();
}
}, [isAuthenticated]);
if (isAuthenticated) {
return <>{children}</>;
}
return null;
};
function MobileNavigation() {
return (
@ -74,12 +55,5 @@ export default async function Layout({
);
}
if (isSelfHosted) {
return (
<Auth>
<SidebarLayout />
</Auth>
);
}
return <SidebarLayout />;
}

View file

@ -4,6 +4,7 @@ import { NextResponse } from "next/server";
import withAuth from "next-auth/middleware";
import { initGuest } from "@/app/guest";
import { isSelfHosted } from "@/utils/constants";
const supportedLocales = Object.keys(languages);
@ -45,7 +46,26 @@ export const middleware = withAuth(
{
secret: process.env.SECRET_PASSWORD,
callbacks: {
authorized: () => true, // needs to be true to allow access to all pages
authorized: ({ token, req }) => {
const nextUrl = req.nextUrl;
if (
isSelfHosted &&
token?.email === null &&
!(
nextUrl.pathname.startsWith("/invite") ||
nextUrl.pathname.startsWith("/login") ||
nextUrl.pathname.startsWith("/register") ||
nextUrl.pathname.startsWith("/auth") ||
nextUrl.pathname.startsWith("/p")
)
) {
// limit which pages guests can access for self-hosted instances
return false;
}
return true;
},
},
},
);