feat: add auth middleware protecting /compare and /profile routes
This commit is contained in:
@@ -1,20 +1,29 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { auth } from "@/lib/auth";
|
import { auth } from "@/lib/auth";
|
||||||
|
|
||||||
const publicPaths = ["/sign-in", "/sign-up", "/api/auth"];
|
const publicPaths = ["/", "/explore", "/sign-in", "/sign-up", "/api/auth"];
|
||||||
|
const protectedPaths = ["/compare", "/profile"];
|
||||||
|
|
||||||
export async function middleware(request: NextRequest) {
|
export async function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl;
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
|
if (
|
||||||
|
pathname.startsWith("/_next") ||
|
||||||
|
pathname.startsWith("/favicon") ||
|
||||||
|
pathname.includes(".")
|
||||||
|
) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
const isPublic = publicPaths.some(
|
const isPublic = publicPaths.some(
|
||||||
(path) => pathname === path || pathname.startsWith(path + "/"),
|
(path) => pathname === path || pathname.startsWith(path + "/"),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isPublic) {
|
const isProtected = protectedPaths.some(
|
||||||
return NextResponse.next();
|
(path) => pathname === path || pathname.startsWith(path + "/"),
|
||||||
}
|
);
|
||||||
|
|
||||||
if (pathname.startsWith("/_next") || pathname.startsWith("/favicon")) {
|
if (isPublic && !isProtected) {
|
||||||
return NextResponse.next();
|
return NextResponse.next();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,7 +31,7 @@ export async function middleware(request: NextRequest) {
|
|||||||
headers: request.headers,
|
headers: request.headers,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!session) {
|
if (!session && isProtected) {
|
||||||
const signInUrl = new URL("/sign-in", request.url);
|
const signInUrl = new URL("/sign-in", request.url);
|
||||||
signInUrl.searchParams.set("callbackUrl", pathname);
|
signInUrl.searchParams.set("callbackUrl", pathname);
|
||||||
return NextResponse.redirect(signInUrl);
|
return NextResponse.redirect(signInUrl);
|
||||||
|
|||||||
Reference in New Issue
Block a user