-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.js
65 lines (54 loc) · 1.72 KB
/
middleware.js
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
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
export default async function middleware(request) {
if (request.nextUrl.pathname.startsWith("/dashboard")) {
if (!request.cookies.has("token")) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
try {
const token = request.cookies.get("token");
const verify = await jwtVerify(
token.value,
new TextEncoder().encode(process.env.JWT_SECRET_KEY),
);
const response = NextResponse.next();
response.cookies.set({
name: "fullname",
value: verify.payload.fullname,
expires: verify.payload.exp * 1000,
path: "/",
});
return response;
} catch (error) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
}
if (request.nextUrl.pathname.startsWith("/rooms")) {
if (!request.cookies.has("token")) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
try {
const token = request.cookies.get("token");
const verify = await jwtVerify(
token.value,
new TextEncoder().encode(process.env.JWT_SECRET_KEY),
);
const response = NextResponse.next();
response.cookies.set({
name: "fullname",
value: verify.payload.fullname,
expires: verify.payload.exp * 1000,
path: "/",
});
return response;
} catch (error) {
return NextResponse.redirect(new URL("/auth/login", request.url));
}
}
if (request.nextUrl.pathname.startsWith("/auth")) {
if (request.cookies.has("token")) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
return NextResponse.next();
}
}