Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
75 lines (62 loc) · 1.94 KB
/
Copy pathproxy.ts
File metadata and controls
75 lines (62 loc) · 1.94 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
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifySession } from "@/lib/auth";
const AUTH_COOKIE = "lorawan_auth";
const PUBLIC_PATHS = new Set([
"/",
"/demo",
"/docs",
"/status",
"/robots.txt",
"/sitemap.xml",
"/opengraph-image",
"/icon.svg",
"/login",
"/api/auth/login",
"/api/auth/logout",
"/api/auth/setup", // Allow setup
"/api/lorawan/webhook",
"/api/v1/ingest", // Allow public ingestion
"/api/health",
"/api/maintenance/cleanup",
]);
const PUBLIC_ASSET = /\.(?:avif|css|gif|ico|jpe?g|js|png|svg|webp|woff2?)$/i;
export async function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
const host = req.headers.get("host")?.split(":")[0];
if (host === "app.uplotr.com" && pathname === "/") {
const appUrl = req.nextUrl.clone();
appUrl.pathname = "/app";
return NextResponse.redirect(appUrl);
}
// `/_vercel/insights/*` is where the Web Analytics script and its beacons
// live. These are extensionless paths, so without this they fall through to
// the redirect below and every anonymous page view is bounced to /login.
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/_vercel/") ||
PUBLIC_ASSET.test(pathname) ||
pathname.startsWith("/docs/")
) {
return NextResponse.next();
}
if (PUBLIC_PATHS.has(pathname)) {
return NextResponse.next();
}
const cookieValue = req.cookies.get(AUTH_COOKIE)?.value;
// Verify JWT
const session = cookieValue ? await verifySession(cookieValue) : null;
if (session) {
return NextResponse.next();
}
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = req.nextUrl.clone();
loginUrl.pathname = "/login";
loginUrl.searchParams.set("next", pathname);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: ["/((?!_next/static|_next/image).*)"],
};