forked from jzakotnik/openlibry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
75 lines (72 loc) · 2.35 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
import { withAuth } from "next-auth/middleware";
import { NextRequest, NextResponse } from "next/server";
export default withAuth(
function middleware(req: NextRequest) {
//console.log("Middleware triggered with ", req);
//set CSP headers
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
//console.log("Nonce", nonce);
const cspHeader = `
default-src 'self' 'nonce-${nonce}' 'unsafe-eval' 'unsafe-inline';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline' 'unsafe-eval';
img-src 'self' blob: data:;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
block-all-mixed-content;
upgrade-insecure-requests;
`;
const requestHeaders = new Headers(req.headers);
if (process.env.SECURITY_HEADERS != "insecure") {
requestHeaders.set("x-nonce", nonce);
requestHeaders.set(
"Content-Security-Policy",
// Replace newline characters and spaces
cspHeader.replace(/\s{2,}/g, " ").trim()
);
}
if (req.nextUrl.pathname == "/admin") {
////console.log("Admin page fetched");
return new NextResponse("No admin", {
status: 400,
});
}
return NextResponse.next({
headers: requestHeaders,
request: {
headers: requestHeaders,
},
});
},
{
callbacks: {
authorized: ({ req, token }) => {
//console.log("Middleware request:", req);
//console.log("Middleware received the token:", token);
//console.log("Middleware caught path:", req.nextUrl.pathname);
//console.log("Middleware role:", req.headers);
//we need the auth endpoint do be without authorization available
/*console.log(
"Do we have authorization enabled?",
process.env.AUTH_ENABLED
);*/
//I think we don't need the endpoint since everything is handled in the ..nextAuth.ts
if (
token === null &&
req.nextUrl.pathname != "/auth/login" &&
req.nextUrl.pathname != "/auth/error" &&
process.env.AUTH_ENABLED == "true"
) {
//console.log("Middleware: not authorized");
//if (token === null) {
return false;
}
//console.log("Middleware: authorized");
return true;
},
},
}
);