-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
68 lines (58 loc) · 1.94 KB
/
Copy pathproxy.ts
File metadata and controls
68 lines (58 loc) · 1.94 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
56
57
58
59
60
61
62
63
64
65
66
67
68
import { NextRequest, NextResponse } from "next/server"
/**
* Middleware to protect Studio routes with HTTP Basic Authentication
* Applies to /studio and /api/studio routes
*/
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
// Check if the path requires authentication
if (pathname.startsWith('/studio') || pathname.startsWith('/api/studio')) {
// Get credentials from environment variables
const authUser = process.env.STUDIO_BASIC_AUTH_USER
const authPass = process.env.STUDIO_BASIC_AUTH_PASS
// If credentials are not set, allow access (for development)
if (!authUser || !authPass) {
console.warn("Studio Basic Auth credentials not configured. Allowing access for development.")
return NextResponse.next()
}
// Check for Basic Auth header
const authHeader = request.headers.get('authorization')
if (!authHeader || !authHeader.startsWith('Basic ')) {
return createAuthResponse()
}
// Verify credentials
try {
const base64Credentials = authHeader.split(' ')[1]
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii')
const [username, password] = credentials.split(':')
if (username !== authUser || password !== authPass) {
return createAuthResponse()
}
} catch {
return createAuthResponse()
}
}
// Allow request to proceed
return NextResponse.next()
}
/**
* Creates a 401 Unauthorized response with Basic Auth challenge
*/
function createAuthResponse(): NextResponse {
return new NextResponse(
JSON.stringify({ error: 'Authentication required' }),
{
status: 401,
headers: {
'Content-Type': 'application/json',
'WWW-Authenticate': 'Basic realm="Lesson Studio"'
}
}
)
}
/**
* Configure the matcher to specify which paths the middleware should run on
*/
export const config = {
matcher: ['/studio/:path*', '/api/studio/:path*']
}