-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
51 lines (42 loc) · 1.47 KB
/
middleware.ts
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
import { jwtVerify, errors as joseErrors } from "jose";
import { NextResponse } from "next/server";
export const config = {
matcher: [
"/api/admin/:path*",
"/api/contacts/:path*",
"/api/emails/:path*",
"/api/groups/:path*",
"/api/users/:path*",
],
};
export async function middleware(req) {
const token = req.headers.get("Authorization")?.split(" ")[1];
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET || "secret");
const { payload } = await jwtVerify(token, secret);
// Check if the token has expired
if (payload.exp && Date.now() >= payload.exp * 1000) {
return NextResponse.json({ error: "Token expired" }, { status: 401 });
}
// Pass decoded payload values to the response headers
const res = NextResponse.next();
if (payload.id) res.headers.set("X-User-Id", payload.id.toString());
if (payload.role) res.headers.set("X-User-Role", String(payload.role));
return res;
} catch (error) {
if (error instanceof joseErrors.JWTExpired) {
return NextResponse.json({ error: "Token expired" }, { status: 401 });
}
if (error instanceof joseErrors.JWTInvalid) {
return NextResponse.json({ error: "Invalid token" }, { status: 401 });
}
console.error("Middleware error:", error);
return NextResponse.json(
{ error: "Authentication failed" },
{ status: 401 }
);
}
}