-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
86 lines (75 loc) · 2.24 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
import { NextRequest, NextResponse } from "next/server";
import { createWallet, getAddress } from "./auth";
import { Sequencer } from "./sequencer";
export async function middleware(request: NextRequest) {
const readRequest = request.method === "GET" || request.method === "HEAD";
let session = request.cookies.get("session")?.value;
let address: string | null = null;
if (session) {
address = await getAddress(session);
} else {
const wallet = await createWallet();
address = wallet.walletAddress;
session = wallet.id;
}
if (readRequest) {
let response = NextResponse.next();
if (!request.cookies.get("session")?.value) {
request.cookies.set({
name: "session",
value: session,
});
response = NextResponse.next({
request,
});
response.cookies.set({
name: "session",
value: session,
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
});
}
return response;
}
if (process.env.MODE === "replay") {
if (request.headers.get("x-sequencer") !== process.env.SEQUENCER_SECRET) {
return Response.json(
{
success: false,
message: "Only sequencer can perform action in replay mode.",
},
{ status: 401 }
);
}
return NextResponse.next({
request,
});
}
const body = await request.text();
await Sequencer.enqueue({
method: request.method,
path: request.nextUrl.pathname,
headers: {
accept: request.headers.get("accept") || "*/*",
"content-type": request.headers.get("content-type"),
"next-action": request.headers.get("next-action"),
"next-router-state-tree": request.headers.get("next-router-state-tree"),
},
body,
address,
});
const response = await fetch(request.url, {
method: request.method,
headers: {
cookie: `session=${session};`,
accept: request.headers.get("accept") || "*/*",
"content-type": request.headers.get("content-type"),
"next-action": request.headers.get("next-action"),
"next-router-state-tree": request.headers.get("next-router-state-tree"),
} as any,
body,
});
await Sequencer.next();
return response;
}