-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
36 lines (31 loc) · 1005 Bytes
/
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
import { NextRequest, NextResponse } from 'next/server';
export const config = {
matcher: '/admin(/login)?'
};
export function middleware(req: NextRequest) {
const url = req.nextUrl;
if (req.url === '/admin/authenticate') {
return;
}
const basicAuth = req.cookies.get('authorization');
if (basicAuth) {
const [user, pwd] = atob(basicAuth.value).split(':');
console.log(url.pathname);
if (user === process.env.ADMIN_USER && pwd === process.env.ADMIN_PWD) {
if (url.pathname.startsWith('/admin/login')) {
url.pathname = '/admin';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
}
if (url.pathname.startsWith('/admin/login')) {
return NextResponse.next();
}
url.pathname = '/admin/login';
return NextResponse.redirect(url, {
headers: {
'WWW-authenticate': 'Basic realm="Secure Area"'
}
});
}