-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproxy.ts
More file actions
61 lines (49 loc) · 1.44 KB
/
Copy pathproxy.ts
File metadata and controls
61 lines (49 loc) · 1.44 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { NextResponse, NextRequest } from "next/server";
import { authLimiter } from "./lib/rate-limit/rate-limit";
export async function proxy(req: NextRequest) {
const { pathname, origin } = req.nextUrl;
// Only limit real login attempts
if (
req.method === "POST" &&
(pathname.startsWith("/api/auth/signin") ||
pathname.startsWith("/api/auth/signin/email"))
) {
const ip =
req.headers.get("x-forwarded-for") ??
req.headers.get("x-real-ip") ??
"anonymous";
let id = req.cookies.get("rlid")?.value;
if (!id) {
id = crypto.randomUUID();
}
// Now TS knows id is definitely a string
const key = `${ip}:${id}`;
const { success, remaining, reset } = await authLimiter.limit(key);
if (!success) {
const url = new URL("/", origin);
url.searchParams.set("error", "rate_limited");
url.searchParams.set("remaining", remaining.toString());
url.searchParams.set("reset", reset.toString());
const res = NextResponse.redirect(url);
res.cookies.set("rlid", id, {
httpOnly: true,
maxAge: 60 * 60,
path: "/",
sameSite: "lax",
});
return res;
}
const res = NextResponse.next();
res.cookies.set("rlid", id, {
httpOnly: true,
maxAge: 60 * 60,
path: "/",
sameSite: "lax",
});
return res;
}
return NextResponse.next();
}
export const config = {
matcher: ["/api/auth/:path*"],
};