-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmiddleware.js
More file actions
77 lines (66 loc) · 1.86 KB
/
Copy pathmiddleware.js
File metadata and controls
77 lines (66 loc) · 1.86 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
76
77
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api)(.*)"],
};
const restrictedRoutes = [
{
start: "/me",
include: ["/me", "/me/dashboard", "/me/settings", "/me/groups"],
rewrite: "/me",
redirect: "/login",
},
{
start: "/user",
redirect: "/login",
},
{
start: "/group",
redirect: "/login",
},
{
start: "/admin",
redirect: "/login",
},
];
const isAuthenticated = async (req) => {
const token = req.cookies.get("token")?.value;
if (!token) return false;
try {
const secret = new TextEncoder().encode(
process.env.REFRESH_TOKEN_SECRET,
);
const { payload } = await jwtVerify(token, secret, {
issuer: "mnemefeast",
audience: "mnemefeast",
});
return !!payload.id;
} catch (error) {
console.error(error);
return false;
}
};
export async function middleware(req) {
const { pathname } = req.nextUrl;
if (pathname.startsWith("/api")) {
// Will need to check for Authorization header
return NextResponse.next();
}
restrictedRoutes.forEach(async (route) => {
if (pathname.startsWith(route.start)) {
if (!(await isAuthenticated(req))) {
return NextResponse.redirect(new URL(route.redirect, req.url));
} else {
if (route.include) {
if (!route.include.includes(pathname)) {
return NextResponse.redirect(
new URL(route.rewrite, req.url),
);
}
}
return NextResponse.next();
}
}
});
return NextResponse.next();
}