-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathmiddleware.ts
50 lines (44 loc) · 1.57 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
import { Configuration } from '@/app/config/config';
import { withAuth } from 'next-auth/middleware';
import { NextRequest, NextResponse, userAgent } from 'next/server';
const authMiddleware = withAuth({});
// attempt to compare strings with constant time,
// nextjs edge runtime can't access crypto.timingSafeEqual
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let ret = 0;
for (let i = 0; i < a.length; i++) {
ret |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return ret === 0;
}
export default async function middleware(req: NextRequest, resp: NextResponse) {
const agent = userAgent(req);
const xForwardedFor = req.headers.get('x-forwarded-for');
if (Configuration.authentication.PEERDB_PASSWORD) {
const authheader = req.headers.get('authorization');
if (authheader && /^basic /i.test(authheader)) {
const auth = atob(authheader.slice(6));
if (
auth[0] !== ':' ||
!safeEqual(auth.slice(1), Configuration.authentication.PEERDB_PASSWORD)
) {
return new NextResponse(null, { status: 403 });
}
} else {
const authRes = await (authMiddleware as any)(req);
if (authRes) return authRes;
}
}
const res = NextResponse.next();
console.log(
`[${req.method} ${req.url}] [${xForwardedFor}] (${JSON.stringify(agent.device)} ${JSON.stringify(agent.os)} ${JSON.stringify(agent.browser)}) ${res.status}`
);
return res;
}
export const config = {
matcher: [
// Match everything other than static assets
'/((?!_next/static/|images/|favicon.ico$).*)',
],
};