-
Notifications
You must be signed in to change notification settings - Fork 38
/
middleware.ts
87 lines (74 loc) · 2.19 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
import { NextResponse } from "next/server";
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { get } from "@vercel/edge-config";
import createMiddleware from "next-intl/middleware";
import { kvKeys } from "@/config/kv";
import { env } from "@/env.mjs";
import countries from "@/lib/countries.json";
import { getIP } from "@/lib/ip";
import { redis } from "@/lib/redis";
import { defaultLocale, localePrefix, locales } from "./config";
export const config = {
matcher: [
"/",
"/(zh|en)/:path*",
"/((?!static|.*\\..*|_next).*)",
], // Run middleware on API routes],
};
const isProtectedRoute = createRouteMatcher([
"/:locale/app(.*)",
"/:locale/admin(.*)",
]);
const isPublicRoute = createRouteMatcher(["/api/webhooks(.*)"]);
const nextIntlMiddleware = createMiddleware({
defaultLocale,
locales,
localePrefix,
});
export default clerkMiddleware(async (auth, req) => {
const { userId, redirectToSignIn } = auth();
if (isPublicRoute(req)) {
return;
}
if (isProtectedRoute(req)) {
if (!userId) {
return redirectToSignIn();
}
auth().protect();
}
const { geo, nextUrl } = req;
const isApi = nextUrl.pathname.startsWith("/api/");
if (process.env.EDGE_CONFIG && env.VERCEL_ENV !== "development") {
const blockedIPs = await get<string[]>("blocked_ips");
const ip = getIP(req);
console.log("ip-->", ip);
if (blockedIPs?.includes(ip)) {
if (isApi) {
return NextResponse.json(
{ error: "You have been blocked." },
{ status: 403 },
);
}
nextUrl.pathname = "/blocked";
return NextResponse.rewrite(nextUrl);
}
if (nextUrl.pathname === "/blocked") {
nextUrl.pathname = "/";
return NextResponse.redirect(nextUrl);
}
}
if (geo && !isApi && env.VERCEL_ENV !== "development") {
console.log("geo-->", geo);
const country = geo.country;
const city = geo.city;
const countryInfo = countries.find((x) => x.cca2 === country);
if (countryInfo) {
const flag = countryInfo.flag;
await redis.set(kvKeys.currentVisitor, { country, city, flag });
}
}
if (isApi) {
return;
}
return nextIntlMiddleware(req);
});