-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmiddleware.ts
More file actions
87 lines (75 loc) · 2.56 KB
/
Copy pathmiddleware.ts
File metadata and controls
87 lines (75 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// middleware.ts
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
import { ENV } from "./lib/constants";
export default withAuth(
async function middleware(req) {
const { pathname, origin} = req.nextUrl;
// QA lockdown - block EVERYTHING except QA gate routes
if (ENV === "QA") {
const token = req.nextauth.token;
const bypassCookie = req.cookies.get("qa_verified")?.value;
// ONLY allow QA gate routes and essential API routes
const isQAGateRoute =
pathname.startsWith("/qa-gate") ||
pathname.startsWith("/api/qa-gate") ||
pathname.startsWith("/api/qa-logout") ||
pathname.startsWith("/api/auth"); // NextAuth API routes
// If QA gate route, allow through
if (isQAGateRoute) {
return NextResponse.next();
}
// For ALL other routes (including /login), check QA bypass first
if (!bypassCookie) {
return NextResponse.redirect(new URL("/qa-gate", origin));
}
// After QA bypass is confirmed, check NextAuth requirements
// Allow /login page since user has passed QA gate
if (pathname === "/" || pathname === "/login" || pathname.startsWith("/onboarding")) {
return NextResponse.next();
}
// For all other protected routes, also require NextAuth token
if (!token) {
return NextResponse.redirect(new URL("/", origin));
}
}
return NextResponse.next();
},
{
callbacks: {
authorized: ({ token, req }) => {
const { pathname } = req.nextUrl;
// For QA environment, let the main middleware handle all authorization
if (ENV === "QA") {
return true;
}
// Always allow these public routes in non-QA environments
if (
pathname === "/" ||
pathname === "/login" ||
pathname.startsWith("/onboarding") ||
pathname.startsWith("/api/auth")
) {
return true;
}
// For non-QA environments, require token for protected routes
return !!token;
},
},
//pages: {
// signIn: "/login",
//},
}
);
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - public files (images, etc.)
*/
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:png|jpg|jpeg|gif|svg|ico|webp)$).*)",
],
};