← back to Omega Watches 2

src/app/api/auth/login/route.ts

47 lines

import { NextRequest, NextResponse } from "next/server";
import { verifyCredentials, createSession, COOKIE_NAME } from "@/lib/auth";

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

    if (!username || !password) {
      return NextResponse.json(
        { success: false, error: { code: "MISSING_CREDENTIALS", message: "Username and password required" } },
        { status: 400 }
      );
    }

    const { valid, role } = await verifyCredentials(username, password);

    if (!valid) {
      return NextResponse.json(
        { success: false, error: { code: "INVALID_CREDENTIALS", message: "Invalid username or password" } },
        { status: 401 }
      );
    }

    const token = await createSession(username, username, role);

    const response = NextResponse.json({
      success: true,
      data: { username, role, token },
    });

    response.cookies.set(COOKIE_NAME, token, {
      httpOnly: true,
      secure: false,
      sameSite: "lax",
      maxAge: 86400,
      path: "/",
    });

    return response;
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: { code: "LOGIN_ERROR", message: error.message } },
      { status: 500 }
    );
  }
}