Self-Hosting Update (#842)

This commit is contained in:
Luke Vella 2023-09-11 15:34:55 +01:00 committed by GitHub
parent 3e616d1e41
commit 7a5f9ae474
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 945 additions and 781 deletions

View file

@ -10,26 +10,37 @@ const publicPaths = ["/login", "/register", "/invite", "/auth"];
// these paths always require authentication
const protectedPaths = ["/settings/billing", "/settings/profile"];
const checkLoginRequirements = async (req: NextRequest, res: NextResponse) => {
const session = await getSession(req, res);
const isGuest = session.user?.isGuest !== false;
if (!isGuest) {
// already logged in
return false;
}
// TODO (Luke Vella) [2023-09-11]: We should handle this on the client-side
if (process.env.NEXT_PUBLIC_SELF_HOSTED === "true") {
// when self-hosting, only public paths don't require login
return !publicPaths.some((publicPath) =>
req.nextUrl.pathname.startsWith(publicPath),
);
} else {
// when using the hosted version, only protected paths require login
return protectedPaths.some((protectedPath) =>
req.nextUrl.pathname.includes(protectedPath),
);
}
};
export async function middleware(req: NextRequest) {
const { headers, cookies, nextUrl } = req;
const newUrl = nextUrl.clone();
const res = NextResponse.next();
const session = await getSession(req, res);
// a protected path is one that requires to be logged in
const isProtectedPath = protectedPaths.some((protectedPath) =>
req.nextUrl.pathname.includes(protectedPath),
);
const isLoginRequired = await checkLoginRequirements(req, res);
const isProtectedPathDueToRequiredAuth =
process.env.AUTH_REQUIRED === "true" &&
!publicPaths.some((publicPath) =>
req.nextUrl.pathname.startsWith(publicPath),
);
const isGuest = session.user?.isGuest !== false;
if (isGuest && (isProtectedPathDueToRequiredAuth || isProtectedPath)) {
if (isLoginRequired) {
newUrl.pathname = "/login";
newUrl.searchParams.set("redirect", req.nextUrl.pathname);
return NextResponse.redirect(newUrl);