import { NextResponse } from 'next/server'; import { db } from '@/lib/db'; import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import { cookies } from 'next/headers'; const JWT_SECRET = process.env.JWT_SECRET || 'super-secret-key-12345'; export async function POST(request: Request) { try { const { email, password } = await request.json(); if (!email || !password) { return NextResponse.json({ error: 'Email ve şifre zorunludur.' }, { status: 400 }); } const res = await db.query('SELECT * FROM admin_users WHERE email = $1', [email]); const user = res.rows[0]; if (!user || (!user.password_hash && password !== 'password123')) { return NextResponse.json({ error: 'Geçersiz email veya şifre.' }, { status: 401 }); } // Verify password let isValid = false; if (user.password_hash) { isValid = await bcrypt.compare(password, user.password_hash); } else if (password === 'password123') { // Fallback if someone forgot to run the init script isValid = true; } if (!isValid) { return NextResponse.json({ error: 'Geçersiz email veya şifre.' }, { status: 401 }); } // Generate token const token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET, { expiresIn: '1d', }); // Set cookie const cookieStore = await cookies(); cookieStore.set('admin_session', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 60 * 60 * 24, // 1 day }); return NextResponse.json({ success: true, user: { id: user.id, email: user.email } }); } catch (error: any) { console.error('Login error:', error); return NextResponse.json({ error: 'Giriş sırasında bir hata oluştu.' }, { status: 500 }); } }