auth redirect updated for portal

This commit is contained in:
makearmy 2025-09-27 14:41:56 -04:00
parent 7b897e3672
commit bce0c5063b
5 changed files with 85 additions and 120 deletions

View file

@ -4,18 +4,15 @@ import { NextResponse, NextRequest } from "next/server";
const PUBLIC_PATHS = new Set<string>([
"/auth/sign-in",
"/auth/sign-up",
// add oauth/callback endpoints here if you use them, e.g.: "/auth/callback"
]);
// If you have additional public pages (e.g., marketing), add them here.
// Keep API endpoints out of this middleware unless you explicitly want to block them.
export function middleware(req: NextRequest) {
const { pathname, search } = req.nextUrl;
const isPublic = isPublicPath(pathname);
const { pathname } = req.nextUrl;
const isAuthRoute = pathname.startsWith("/auth/");
const token = req.cookies.get("ma_at")?.value ?? "";
// 1) If already authed and on an auth route, dump to /portal
// If already authed and hitting an auth route, always go to the portal
if (token && isAuthRoute) {
const url = req.nextUrl.clone();
url.pathname = "/portal";
@ -23,26 +20,22 @@ export function middleware(req: NextRequest) {
return NextResponse.redirect(url);
}
// 2) If not authed and path is protected → send to sign-in with next=<original>
if (!token && !isPublic) {
// If not authed and path is protected → send to sign-in (no ?next=)
if (!token && !isPublicPath(pathname)) {
const url = req.nextUrl.clone();
url.pathname = "/auth/sign-in";
// Default to /portal after login, but preserve deep-link if present
const next = pathname + (search || "");
url.search = next ? `?next=${encodeURIComponent(next)}` : `?next=${encodeURIComponent("/portal")}`;
url.search = ""; // IMPORTANT: drop next so login always goes to /portal
return NextResponse.redirect(url);
}
// 3) Otherwise, allow through
return NextResponse.next();
}
// Helpers
function isPublicPath(pathname: string): boolean {
// Public routes
if (PUBLIC_PATHS.has(pathname)) return true;
// Static assets and framework internals
// Static assets / internals
if (
pathname.startsWith("/_next/") ||
pathname.startsWith("/static/") ||
@ -52,7 +45,7 @@ function isPublicPath(pathname: string): boolean {
pathname === "/sitemap.xml"
) return true;
// API routes: by default we *do not* block /api/* in middleware (let routes handle auth)
// API routes aren't gated here; each route should enforce auth as needed
if (pathname.startsWith("/api/")) return true;
// Everything else is protected
@ -60,7 +53,6 @@ function isPublicPath(pathname: string): boolean {
}
export const config = {
// Run middleware for all paths except the most common static files (belt & suspenders)
matcher: [
"/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)",
],