-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
53 lines (41 loc) · 1.29 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
import { NextRequest, NextResponse } from "next/server";
import { AuthStatus } from "./types/auth";
import "server-only";
export const runtime = "nodejs";
const unauthRoutes = new Set(["/login", "/signup"]);
const authRoutes = new Set(["/", "/dm", "/gc", "/server"]);
export default async function middleware(req: NextRequest) {
if (req.nextUrl.pathname.startsWith("/_next")) return NextResponse.next();
let authStatus: AuthStatus;
try {
const response = await fetch(
`${process.env.BASE_URL}/api/auth/status/${
req.cookies.get("session")?.value
}`
);
const data = await response.json();
if (!response.ok) {
authStatus = "unauthenticated";
}
authStatus = data.authStatus;
} catch (error) {
authStatus = "unauthenticated";
}
const page = getPageName(req.nextUrl.pathname);
if (
(authStatus === "unauthenticated" || authStatus === "signingUp") &&
authRoutes.has(page)
) {
return NextResponse.redirect(new URL("/login", req.url));
}
if (authStatus === "authenticated" && unauthRoutes.has(page)) {
return NextResponse.redirect(new URL("/", req.url));
}
}
function getPageName(path: string) {
let i = 1;
while (i < path.length && path[i] !== "/" && path[1] !== "?") {
i++;
}
return path.slice(0, i + 1);
}