fix: add cookie security attributes and error handling

- Add secure and sameSite attributes to cookie configuration
- Add try-catch block to handle malformed JSON and other errors
- Add validation for missing username or password fields

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-03-04 02:05:55 +08:00
parent bdb4d0cf32
commit 5365352331

View File

@@ -3,21 +3,37 @@ import { NextResponse } from 'next/server';
import { AUTH_USERNAME, AUTH_PASSWORD, COOKIE_NAME, COOKIE_MAX_AGE } from '@/lib/constants'; import { AUTH_USERNAME, AUTH_PASSWORD, COOKIE_NAME, COOKIE_MAX_AGE } from '@/lib/constants';
export async function POST(request: Request) { export async function POST(request: Request) {
const body = await request.json(); try {
const { username, password } = body; const body = await request.json();
const { username, password } = body;
if (username === AUTH_USERNAME && password === AUTH_PASSWORD) { if (!username || !password) {
const response = NextResponse.json({ success: true }); return NextResponse.json(
response.cookies.set(COOKIE_NAME, 'ok', { { error: 'Username and password are required' },
httpOnly: true, { status: 400 }
maxAge: COOKIE_MAX_AGE, );
path: '/', }
});
return response; if (username === AUTH_USERNAME && password === AUTH_PASSWORD) {
const response = NextResponse.json({ success: true });
response.cookies.set(COOKIE_NAME, 'ok', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: COOKIE_MAX_AGE,
path: '/',
});
return response;
}
return NextResponse.json(
{ error: 'Invalid credentials' },
{ status: 401 }
);
} catch (error) {
return NextResponse.json(
{ error: 'Invalid request' },
{ status: 400 }
);
} }
return NextResponse.json(
{ error: 'Invalid credentials' },
{ status: 401 }
);
} }