-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
65 lines (56 loc) · 1.99 KB
/
middleware.ts
File metadata and controls
65 lines (56 loc) · 1.99 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
import { NextRequest, NextResponse } from 'next/server';
/**
* Middleware to protect routes
*
* If ORG_STUDIO_API_KEY is set (auth enabled), redirect to /login if not authenticated.
* Otherwise, allow all access (localhost dev mode).
*/
export function middleware(request: NextRequest) {
const apiKey = process.env.ORG_STUDIO_API_KEY;
// No API key configured — auth is disabled, allow all access
if (!apiKey) {
return NextResponse.next();
}
// Auth is enabled — check if user is authenticated
const pathname = request.nextUrl.pathname;
// Allow login page and auth endpoints without authentication
if (
pathname === '/login' ||
pathname.startsWith('/api/auth/login') ||
pathname.startsWith('/api/auth/logout')
) {
return NextResponse.next();
}
// Check for session cookie or API key
const cookieHeader = request.headers.get('cookie') || '';
const sessionToken = cookieHeader.match(/session_token=([a-f0-9]+)/)?.[1];
const authHeader = request.headers.get('authorization') || '';
const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : '';
// For API routes with Bearer token auth
if (authHeader && bearerToken === apiKey) {
return NextResponse.next();
}
// For browser requests with session cookie
if (sessionToken) {
// Session validation happens in the API routes
// Here we just allow the request to proceed
return NextResponse.next();
}
// No valid auth — redirect to login
return NextResponse.redirect(new URL('/login', request.url));
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - login (login page)
*
* We still need to protect API routes, so we handle those in the route handlers themselves.
*/
'/((?!api|ws|_next/static|_next/image|favicon.ico|login).*)',
],
};