middleware update

This commit is contained in:
makearmy 2025-09-30 10:36:40 -04:00
parent f743532887
commit 543a875169

View file

@ -53,12 +53,18 @@ import { NextResponse, NextRequest } from "next/server";
}
}
/** Build a redirect response to /auth/sign-in and clear auth markers. */
/** Build redirect to /auth/sign-in?reauth=1&next=<original>, and clear auth markers. */
function kickToSignIn(req: NextRequest) {
const orig = new URL(req.url);
const next = orig.pathname + (orig.search || "");
const url = new URL(req.url);
url.pathname = "/auth/sign-in";
url.search = "";
url.searchParams.set("reauth", "1");
url.searchParams.set("next", next);
const res = NextResponse.redirect(url);
// Clear tokens so the very next /auth/* request is truly unauthenticated
res.cookies.set("ma_at", "", { maxAge: 0, path: "/" });
res.cookies.set("ma_v", "", { maxAge: 0, path: "/" }); // throttle marker
// If you also use a refresh token, clear it here too:
@ -86,13 +92,13 @@ import { NextResponse, NextRequest } from "next/server";
const isAuthRoute = pathname.startsWith("/auth/");
const isProtected = !isPublicPath(pathname);
// NEW: allow explicit reauth flow even if a (possibly stale) token cookie exists
// Allow explicit reauth flow even if a (possibly stale) token cookie exists
const forceAuth =
isAuthRoute &&
(url.searchParams.get("reauth") === "1" ||
url.searchParams.get("force") === "1");
// If unauthenticated and the route is protected, send to sign-in
// If unauthenticated and the route is protected, send to sign-in (with next + reauth)
if (!token && isProtected) {
return kickToSignIn(req);
}
@ -133,7 +139,7 @@ import { NextResponse, NextRequest } from "next/server";
});
if (!r.ok) {
// Token no longer valid on the server → force re-auth
// Token no longer valid on the server → force re-auth, carry next
return kickToSignIn(req);
}