-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
55 lines (46 loc) · 1.54 KB
/
middleware.ts
File metadata and controls
55 lines (46 loc) · 1.54 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
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const url = request.nextUrl.pathname;
// Only protect admin routes
if (url.startsWith('/admin') || url.startsWith('/api/admin')) {
const authHeader = request.headers.get('authorization');
// Get credentials from environment variables
const username = process.env.ADMIN_USERNAME || 'admin';
const password = process.env.ADMIN_PASSWORD;
if (!password) {
// If no password is configured, deny access
return new NextResponse('Authentication required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Admin Access"',
},
});
}
if (!authHeader || !authHeader.startsWith('Basic ')) {
return new NextResponse('Authentication required', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Admin Access"',
},
});
}
const base64Credentials = authHeader.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
const [providedUsername, providedPassword] = credentials.split(':');
if (providedUsername !== username || providedPassword !== password) {
return new NextResponse('Invalid credentials', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="Admin Access"',
},
});
}
}
return NextResponse.next();
}
export const config = {
matcher: [
'/admin/:path*',
'/api/admin/:path*',
],
};