-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathmiddleware.ts
100 lines (85 loc) · 2.6 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
99
100
import { NextResponse } from "next/server";
import { geolocation } from "@vercel/functions";
import { auth } from "auth";
import { NextAuthRequest } from "next-auth/lib";
import UAParser from "ua-parser-js";
import { siteConfig } from "./config/site";
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
const redirectMap = {
"Missing[0000]": "/docs/short-urls#missing-links",
"Expired[0001]": "/docs/short-urls#expired-links",
"Disabled[0002]": "/docs/short-urls#disabled-links",
"Error[0003]": "/docs/short-urls#error-links",
};
// 提取短链接处理逻辑
async function handleShortUrl(req: NextAuthRequest) {
if (!req.url.includes("/s/")) return NextResponse.next();
const slug = extractSlug(req.url);
if (!slug)
return NextResponse.redirect(`${siteConfig.url}/docs/short-urls`, 302);
const geo = geolocation(req);
const headers = req.headers;
const { browser, device } = parseUserAgent(headers.get("user-agent") || "");
const trackingData = {
slug,
referer: headers.get("referer") || "(None)",
ip: headers.get("X-Forwarded-For"),
city: geo?.city,
region: geo?.region,
country: geo?.country,
latitude: geo?.latitude,
longitude: geo?.longitude,
flag: geo?.flag,
lang: headers.get("accept-language")?.split(",")[0],
device: device.model || "Unknown",
browser: browser.name || "Unknown",
};
const res = await fetch(`${siteConfig.url}/api/s`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(trackingData),
});
if (!res.ok)
return NextResponse.redirect(
`${siteConfig.url}${redirectMap["Error[0003]"]}`,
302,
);
const target = await res.json();
if (!target || typeof target !== "string") {
return NextResponse.redirect(
`${siteConfig.url}${redirectMap["Error[0003]"]}`,
302,
);
}
if (target in redirectMap) {
return NextResponse.redirect(
`${siteConfig.url}${redirectMap[target]}`,
302,
);
}
return NextResponse.redirect(target, 302);
}
// 提取 slug
function extractSlug(url: string): string | null {
const match = url.match(/([^/?]+)(?:\?.*)?$/);
return match ? match[1] : null;
}
// 解析用户代理
const parser = new UAParser();
function parseUserAgent(ua: string) {
parser.setUA(ua);
return {
browser: parser.getBrowser(),
device: parser.getDevice(),
};
}
export default auth(async (req) => {
try {
return await handleShortUrl(req);
} catch (error) {
console.error("Middleware error:", error);
return NextResponse.redirect(siteConfig.url, 302);
}
});