← back to PoppyPetitions

app/api/auth/login/route.ts

44 lines

import { NextRequest, NextResponse } from 'next/server';
import { createSession, buildAuthCookie } from '@/lib/auth';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { username, password } = body as { username?: string; password?: string };

    if (!username || !password) {
      return NextResponse.json(
        { error: 'Username and password are required' },
        { status: 400 },
      );
    }

    const expectedUsername = process.env.AUTH_USERNAME ?? 'admin';
    const expectedPassword = process.env.AUTH_PASSWORD;
    if (!expectedPassword) {
      console.error('[auth/login] AUTH_PASSWORD env unset — refusing all logins (fail-closed)');
      return NextResponse.json({ error: 'Server misconfigured' }, { status: 500 });
    }

    if (username !== expectedUsername || password !== expectedPassword) {
      return NextResponse.json(
        { error: 'Invalid credentials' },
        { status: 401 },
      );
    }

    const token = createSession(username);
    const cookieValue = buildAuthCookie(token);

    const response = NextResponse.json({ success: true });
    response.headers.set('Set-Cookie', cookieValue);
    return response;
  } catch (err) {
    console.error('[auth/login] Error:', (err as Error).message);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }
}