TKK_E32230469/web_ups/src/proxy.ts

53 lines
1.7 KiB
TypeScript

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { decrypt } from '@/lib/auth';
export default async function proxy(request: NextRequest) {
const path = request.nextUrl.pathname;
// Protect root path and api control
const isProtectedRoute = path === '/' || path.startsWith('/api/control');
if (isProtectedRoute) {
const cookie = request.cookies.get('auth_token')?.value;
const session = await decrypt(cookie);
// If accessing /api/control without cookie, check if they have the bearer token instead
if (path.startsWith('/api/control')) {
const authHeader = request.headers.get('Authorization');
const apiSecret = process.env.CONTROL_API_SECRET;
// If there's an API secret configured, and they provided the right bearer token, let them through
if (apiSecret && authHeader === `Bearer ${apiSecret}`) {
return NextResponse.next();
}
// Otherwise, if they don't have a valid web session cookie, block them
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.next();
}
// For the web dashboard (root), redirect to login if not authenticated
if (!session) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// Redirect authenticated users away from the login page
if (path === '/login') {
const cookie = request.cookies.get('auth_token')?.value;
const session = await decrypt(cookie);
if (session) {
return NextResponse.redirect(new URL('/', request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/', '/login', '/api/control/:path*'],
};