-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.ts
97 lines (84 loc) · 2.82 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import {type NextRequest, NextResponse} from "next/server";
import {jwtVerify} from "jose";
export async function middleware(request: NextRequest) {
if (isProduction()) {
if (isTool(request)) {
return AppMiddleware(request);
}
if (isErrorPage(request)) {
return NextResponse.next();
} else {
return authenticationFailedResponse(request);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico).*)",
],
};
export async function AppMiddleware(request: NextRequest) {
let cookie = request.cookies.get('toolify');
if (!cookie) return authenticationFailedResponse(request);
const {fullKey} = parse(request);
const pathList = fullKey.split("/");
if (pathList.length < 2 || pathList[0] !== "tools") {
return authenticationFailedResponse(request);
}
const toolName = pathList[1];
const secretKey = process.env.TOOLIFY_SHARED_SECRET_KEY;
if (!secretKey) {
console.log("TOOLIFY_SHARED_SECRET_KEY not set")
return authenticationFailedResponse(request);
}
try {
const decodedToken = await verify(cookie.value, secretKey);
if (!decodedToken) {
console.log("Invalid token")
return authenticationFailedResponse(request);
}
const tools: unknown = decodedToken.tools;
const toolsArray = tools as string[];
if (!toolsArray.includes(toolName)) {
console.log("Invalid toolname");
return authenticationFailedResponse(request);
}
return NextResponse.next();
} catch (err) {
console.log("Error decoding token", err);
return authenticationFailedResponse(request);
}
}
function isTool(request: NextRequest) {
const {key} = parse(request);
return key === "tools";
}
function isErrorPage(request: NextRequest) {
const {key} = parse(request);
return key === "error";
}
function isProduction() {
return process.env.NODE_ENV === "production";
}
async function verify(token: string, secret: string) {
const {payload} = await jwtVerify(
token,
new TextEncoder().encode(secret),
);
return payload;
}
function authenticationFailedResponse(request: NextRequest) {
return NextResponse.redirect(new URL("/error/unauthorized", request.url));
}
const parse = (req: NextRequest) => {
let domain = req.headers.get("host") as string;
let path = req.nextUrl.pathname;
const searchParams = req.nextUrl.searchParams.toString();
const fullPath = `${path}${
searchParams.length > 0 ? `?${searchParams}` : ""
}`;
const key = decodeURIComponent(path.split("/")[1]!);
const fullKey = decodeURIComponent(path.slice(1));
return {domain, path, fullPath, key, fullKey};
};