-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
45 lines (37 loc) · 1.23 KB
/
middleware.ts
File metadata and controls
45 lines (37 loc) · 1.23 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
import { jwtVerify } from "jose";
import { NextRequest, NextResponse } from "next/server";
const PUBLIC_PATHS = ["/login", "/api/auth/login", "/api/auth/logout"];
function getSecret() {
const jwt = process.env.JWT_SECRET;
if (!jwt) throw new Error("JWT_SECRET environment variable is required");
return new TextEncoder().encode(jwt);
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (
PUBLIC_PATHS.some((p) => pathname.startsWith(p)) ||
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon")
) {
return NextResponse.next();
}
const token = req.cookies.get("dentai-session")?.value;
if (!token) {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "No autenticado" }, { status: 401 });
}
return NextResponse.redirect(new URL("/login", req.url));
}
try {
await jwtVerify(token, getSecret());
return NextResponse.next();
} catch {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Sesion expirada" }, { status: 401 });
}
return NextResponse.redirect(new URL("/login", req.url));
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};