-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
98 lines (92 loc) · 2.46 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
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
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getIronSession } from "iron-session/edge";
import * as Sentry from "@sentry/nextjs";
export async function middleware(request: NextRequest, response: NextResponse) {
const session = await getIronSession(request, response, {
password: process.env.IRON_SESSION,
cookieName: "jid",
cookieOptions: {
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 1, // 1 hour
},
});
if (!session.user) {
Sentry.captureMessage("No identity presented to middleware", {
tags: {
code: "middleware",
},
});
return new NextResponse(
JSON.stringify({
ok: false,
message: "No identity presented",
}),
{ status: 401, headers: { "content-type": "application/json" } }
);
}
return await queryRedis(session.user.sessionId, session.user.userId, request);
}
/*
* Function to query redis and check if session in cookie matches session stored
*/
async function queryRedis(
sessionId: string,
userId: string,
request: NextRequest
) {
const redisQuery = await fetch(
process.env.UPSTASH_FETCH_API_URL + `/hget/sessions/${sessionId}`,
{
headers: {
Authorization: `Bearer ${process.env.UPSTASH_FETCH_API_TOKEN}`,
},
}
);
if (redisQuery.ok) {
const data = await redisQuery.json();
if (data.result === userId) {
const requestHeaders = new Headers(request.headers);
requestHeaders.set("user", data.result);
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
});
return response;
} else {
Sentry.captureMessage("No identity presented to middleware", {
tags: {
code: "middleware",
},
});
return new NextResponse(
JSON.stringify({
ok: false,
message: "Invalid identity presented",
}),
{ status: 401, headers: { "content-type": "application/json" } }
);
}
} else {
Sentry.captureMessage(redisQuery.statusText, {
tags: {
code: "middleware",
},
});
return new NextResponse(
JSON.stringify({
ok: false,
message: redisQuery.statusText,
}),
{
status: redisQuery.status,
headers: { "content-type": "application/json" },
}
);
}
}
export const config = {
matcher: "/api/comments/:path*",
};