Repository navigation
Expand file tree
/
Copy pathmiddleware.ts
More file actions
240 lines (209 loc) · 7.17 KB
/
Copy pathmiddleware.ts
File metadata and controls
240 lines (209 loc) · 7.17 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { authMiddleware } from "./lib/auth/middleware";
import { csrfAdapter } from "./lib/csrf";
import { verifyJwtPayload } from "./lib/auth/jwt-edge";
const redirectMap: Record<string, string> = {
"/auth": "/auth/login",
"/register": "/auth/register",
"/login": "/auth/login"
};
const forbiddenFragments = [
".env",
".git",
"package.json",
"tsconfig",
"next.config",
];
// Middleware principal
export async function middleware(
request: NextRequest,
): Promise<NextResponse | Response> {
const token = request.cookies.get("auth_token")?.value;
const currentPath = request.nextUrl.pathname;
const normalisedPath =
currentPath.endsWith("/") && currentPath !== "/"
? currentPath.slice(0, -1)
: currentPath;
// If there is an active session (token cookie present) and the user
// is trying to access the login page, redirect them to profile to
// avoid showing the login UI to already-authenticated users.
if (token && (normalisedPath === "/auth/login" || normalisedPath === "/login" || normalisedPath === "/auth")) {
const decoded = await verifyJwtPayload(token);
if (decoded?.sub) {
const url = request.nextUrl.clone();
url.pathname = `/profile/${decoded.sub}`;
url.search = "";
return NextResponse.redirect(url, 308);
}
// Token inválido — dejar pasar para que se autentique de nuevo
}
const redirectTarget = redirectMap[normalisedPath];
if (redirectTarget) {
const url = request.nextUrl.clone();
url.pathname = redirectTarget;
url.search = "";
return NextResponse.redirect(url, 308);
}
const lowerPath = currentPath.toLowerCase();
const hasTraversal = lowerPath.includes("..") || lowerPath.includes("%2e%2e");
const touchesForbidden = forbiddenFragments.some((fragment) =>
lowerPath.includes(fragment),
);
if (hasTraversal || touchesForbidden) {
if (currentPath.startsWith("/api")) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
if (currentPath !== "/not-found") {
const notFoundUrl = request.nextUrl.clone();
notFoundUrl.pathname = "/not-found";
notFoundUrl.search = "";
return NextResponse.redirect(notFoundUrl, 308);
}
return NextResponse.rewrite(request.nextUrl);
}
// Si no hay token y es ruta protegida, redirigir a login
if (!token && isProtectedPath(currentPath)) {
const loginUrl = new URL("/auth/login", request.url);
return NextResponse.redirect(loginUrl);
}
// Verificar roles para rutas de admin y sus endpoints de API
if (currentPath.startsWith("/admin") || currentPath.startsWith("/api/admin")) {
const roleCheck = await checkUserRole(request, token);
if (roleCheck) {
return roleCheck;
}
}
if (currentPath.startsWith("/content_manager") || currentPath.startsWith("/api/content_manager")) {
const roleCheck = await checkUserRoleAllowed(request, token, ["admin", "content_manager"]);
if (roleCheck) return roleCheck;
}
if (currentPath.startsWith("/leader_proyect") || currentPath.startsWith("/api/leader_proyect")) {
const roleCheck = await checkUserRoleAllowed(request, token, ["admin", "lead_project"]);
if (roleCheck) return roleCheck;
}
// Verificar CSRF para requests que lo requieran
const csrfResult = await verifyCsrf(request);
if (csrfResult) {
return csrfResult;
}
return await authMiddleware(request);
}
// Función helper para verificar rutas protegidas
function isProtectedPath(path: string): boolean {
const protectedPaths = ["/admin", "/content_manager", "/leader_proyect", "/profile", "/attendance"];
return protectedPaths.some((protectedPath) => path.startsWith(protectedPath));
}
// Función helper para denegar acceso
function denyAccess(request: NextRequest): NextResponse {
if (request.nextUrl.pathname.startsWith("/api")) {
return NextResponse.json(
{
error: "403 - Acceso restringido.",
},
{ status: 403 },
);
} else {
return NextResponse.redirect(new URL("/access-denied", request.url));
}
}
// Función para verificar roles de usuario — usa JWT Edge-compatible directamente
// para evitar self-fetch que es inestable en Vercel Edge Runtime.
async function checkUserRole(
request: NextRequest,
token: string | undefined,
): Promise<NextResponse | null> {
if (!token) {
return denyAccess(request);
}
// Verificar rol directamente desde el JWT (Edge-compatible)
const decoded = await verifyJwtPayload(token);
if (!decoded) {
console.error("[Admin middleware] JWT inválido o expirado");
return denyAccess(request);
}
if (decoded.role !== "admin") {
return denyAccess(request);
}
return null;
}
async function checkUserRoleAllowed(
request: NextRequest,
token: string | undefined,
allowedRoles: string[],
): Promise<NextResponse | null> {
if (!token) return denyAccess(request);
const decoded = await verifyJwtPayload(token);
if (!decoded) return denyAccess(request);
if (!allowedRoles.includes(decoded.role ?? "")) return denyAccess(request);
return null;
}
// Función para verificar CSRF
async function verifyCsrf(request: NextRequest): Promise<NextResponse | null> {
const method = request.method;
const path = request.nextUrl.pathname;
// Solo verificar CSRF para métodos que modifican datos
if (!csrfAdapter.requiresCsrfProtection(method)) {
return null;
}
// Excluir rutas públicas que no necesitan CSRF
const publicPaths = [
"/api/auth/login",
"/api/auth/register",
"/api/auth/logout",
"/api/auth/refresh",
"/api/auth/is-admin",
"/api/auth/forgot-password",
"/api/auth/reset-password",
"/api/qr-dinamico",
"/api/asistencia",
"/api/admin/attendances", // Excluir escaneo QR de CSRF
];
if (publicPaths.some((publicPath) => path.startsWith(publicPath))) {
return null;
}
// Obtener tokens
const csrfTokenFromHeader = request.headers.get("x-csrf-token");
const csrfTokenFromCookie = request.cookies.get("csrf_token")?.value;
// Debug logs
console.log("[CSRF] Checking", {
method,
path,
hasHeader: !!csrfTokenFromHeader,
hasCookie: !!csrfTokenFromCookie,
headerSample: csrfTokenFromHeader?.slice(0, 6),
cookieSample: csrfTokenFromCookie?.slice(0, 6),
});
// Verificar que ambos tokens existan y coincidan
if (!csrfTokenFromHeader || !csrfTokenFromCookie) {
console.warn("[CSRF] Missing token", {
hasHeader: !!csrfTokenFromHeader,
hasCookie: !!csrfTokenFromCookie,
});
return NextResponse.json(
{ error: "Token CSRF requerido" },
{
status: 403,
},
);
}
// Debug log antes de la validación
if (!csrfAdapter.validateToken(csrfTokenFromHeader, csrfTokenFromCookie)) {
console.warn("[CSRF] Invalid token", {
headerSample: csrfTokenFromHeader.slice(0, 6),
cookieSample: csrfTokenFromCookie.slice(0, 6),
});
return NextResponse.json(
{ error: "Token CSRF inválido" },
{
status: 403,
},
);
}
return null;
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.(?:svg|png|jpg|jpeg|gif|webp|css|js)$).*)",
],
};