-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
76 lines (62 loc) · 2.57 KB
/
Copy pathproxy.ts
File metadata and controls
76 lines (62 loc) · 2.57 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
realm.rd, Scribble the plans, spill the thoughts.
Copyright (C) 2025 Jayant Hegde Kageri <https://jayantkageri.in/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { cookies, headers } from "next/headers";
import { type NextRequest, NextResponse } from "next/server";
import Config from "@/lib/constant";
import { isConnected, getRedisConnection } from "@/lib/database/connection";
import { verify as verifyToken } from "@/lib/operations/auth";
import { getClientIp } from "@/lib/operations/ip";
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
async function verify(ip: string): Promise<boolean> {
const cookieStore = await cookies();
const cookie = cookieStore.get("session");
if (!cookie?.value) return false;
const auth = await verifyToken(cookie.value, ip || "");
if (auth?.username) return true;
cookieStore.delete("session");
return false;
}
export async function proxy(req: NextRequest) {
const ping = isConnected().both;
const locked = req.nextUrl.pathname === "/locked";
const logout = req.nextUrl.pathname === "/auth/logout";
if (!ping)
return locked
? NextResponse.next()
: NextResponse.redirect(`${Config.DOMAIN}/locked`);
if (locked) return NextResponse.redirect(Config.DOMAIN);
const ip = getClientIp(await headers()) || "";
const verification = await verify(ip);
const login = req.nextUrl.pathname === "/auth/login";
if (!verification) {
const redisConn = await getRedisConnection();
const key = `rate_limit:${ip}`;
const current = await redisConn.incr(key);
if (current === 1) await redisConn.expire(key, 60);
if (current > 20) return new NextResponse(null, { status: 429 });
if (!login || logout)
return NextResponse.redirect(
`${Config.DOMAIN}/auth/login?path=${
logout ? "/" : req.nextUrl.pathname
}`,
);
if (verification && login) return NextResponse.redirect(Config.DOMAIN);
return NextResponse.next();
}
}