-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
53 lines (47 loc) · 1.13 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 { base64url } from "jose";
import { NextRequest, NextResponse, userAgent } from "next/server";
import { isLoggedIn } from "./lib/auth";
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const loggedIn = isLoggedIn(request);
const { device, os } = userAgent(request);
switch (path) {
case "/":
if (!loggedIn) {
return NextResponse.rewrite(new URL("/login", request.url));
}
break;
case "/login":
if (loggedIn) {
return NextResponse.rewrite(new URL("/", request.url));
}
break;
}
const ua = {
device: {
vendor: device.vendor ?? "",
model: device.model ?? "",
},
os: {
name: os.name ?? "",
version: os.version ?? "",
},
};
const response = NextResponse.next();
if (request.cookies.get("ua") === undefined) {
response.cookies.set({
name: "ua",
value: base64url.encode(JSON.stringify(ua)),
path: "/",
maxAge: 15 * 60 * 60 * 24,
httpOnly: false,
});
}
return response;
}
export const config = {
matcher: [
"/",
"/login",
],
};