Files
taller_automotriz/src/middleware.ts
T
Beldor f4df90ac1e
Revisión con IA / ai-review (pull_request) Successful in 1m24s
fix(auth): comprobar el rol de la sesion en todas las rutas
Las tres sesiones (admin, cliente, jefe) se firman con el mismo secreto, asi que
verificar solo la firma alcanzaba para que un token de un rol pasara por la
cookie de otro. Verificado antes del cambio: un token de admin en
cliente_session daba 200 en /api/cliente/autos, y uno de jefe cargaba
/cliente/dashboard. Despues: 401 y 307.

- Las 26 llamadas a verificarSesion pasan el rol esperado.
- El middleware, que hacia su propio jwtVerify sin mirar el rol, ahora tambien
  lo comprueba.
- Se sacan las comprobaciones sueltas de rol en las rutas de jefe, que quedaron
  redundantes.

Matriz probada contra la app: los tres roles siguen entrando en su area (200) y
ninguno entra en la de los otros, ni por API (401) ni por pagina (307).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 16:45:33 -03:00

51 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { jwtVerify } from "jose";
const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "dev-secret");
// Las tres sesiones se firman con el mismo secreto, así que además de la firma hay
// que mirar el rol: si no, un token de jefe en la cookie del cliente pasa.
async function verifyCookie(req: NextRequest, cookieName: string, rol: "admin" | "cliente" | "jefe") {
const token = req.cookies.get(cookieName)?.value;
if (!token) return false;
try {
const { payload } = await jwtVerify(token, SECRET);
return (payload as { role?: string }).role === rol;
} catch {
return false;
}
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (pathname.startsWith("/cliente/dashboard") ||
pathname.startsWith("/cliente/historial") ||
pathname.startsWith("/cliente/perfil") ||
pathname.startsWith("/cliente/turnos")) {
const ok = await verifyCookie(req, "cliente_session", "cliente");
if (!ok) return NextResponse.redirect(new URL("/cliente", req.url));
}
if (pathname.startsWith("/admin/dashboard") ||
pathname.startsWith("/admin/turnos") ||
pathname.startsWith("/admin/historial") ||
pathname.startsWith("/admin/servicios") ||
pathname.startsWith("/admin/jefes") ||
pathname.startsWith("/admin/clientes")) {
const ok = await verifyCookie(req, "admin_session", "admin");
if (!ok) return NextResponse.redirect(new URL("/admin", req.url));
}
if (pathname.startsWith("/jefe/dashboard")) {
const ok = await verifyCookie(req, "jefe_session", "jefe");
if (!ok) return NextResponse.redirect(new URL("/jefe", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/cliente/:path*", "/admin/:path*", "/jefe/:path*"],
};