import { NextResponse } from "next/server"; import { getDb } from "@/lib/db"; import bcrypt from "bcryptjs"; import { cookies } from "next/headers"; import { randomUUID } from "crypto"; export async function POST(request: Request) { try { const sql = getDb(); const { email, password } = await request.json(); if (!email || !password) { return NextResponse.json( { error: "Email and password are required" }, { status: 400 } ); } // Find user const users = await sql( `SELECT u.*, up.can_view_financial, up.can_edit, up.can_create, up.can_delete, up.can_download, up.can_view_dashboard, up.can_view_components, up.can_view_products, up.can_view_customers, up.can_view_suppliers, up.can_view_production, up.can_view_stock_history, up.can_view_logistics, up.can_view_stock_take, up.can_view_settings FROM users u LEFT JOIN user_permissions up ON u.id = up.user_id WHERE u.email = $1 AND u.is_active = true`, [email.toLowerCase()] ); if (users.length === 0) { return NextResponse.json( { error: "Invalid email or password" }, { status: 401 } ); } const user = users[0]; // Verify password const isValid = await bcrypt.compare(password, user.password_hash); if (!isValid) { return NextResponse.json( { error: "Invalid email or password" }, { status: 401 } ); } // Create session const sessionToken = randomUUID(); const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days await sql( `INSERT INTO sessions (user_id, token, expires_at) VALUES ($1, $2, $3)`, [user.id, sessionToken, expiresAt.toISOString()] ); // Set cookie const cookieStore = await cookies(); cookieStore.set("session_token", sessionToken, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", expires: expiresAt, path: "/", }); // Build sections array from individual flags const sections: string[] = []; if (user.can_view_dashboard) sections.push("dashboard"); if (user.can_view_components) sections.push("components"); if (user.can_view_products) sections.push("products"); if (user.can_view_customers) sections.push("customers"); if (user.can_view_suppliers) sections.push("suppliers"); if (user.can_view_production) sections.push("production"); if (user.can_view_stock_history) sections.push("stock-history"); if (user.can_view_logistics) sections.push("logistics"); if (user.can_view_stock_take) sections.push("stock-take"); if (user.can_view_settings || user.role === "admin") sections.push("settings"); return NextResponse.json({ user: { id: user.id, email: user.email, name: user.name, role: user.role, permissions: { sections, can_view_financial: user.can_view_financial ?? false, can_edit: user.can_edit ?? false, can_create: user.can_create ?? false, can_delete: user.can_delete ?? false, can_download: user.can_download ?? false, }, }, }); } catch (error) { console.error("Login error:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }