♻️ 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

@ -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;
},
},
},
);