Files
Pay2Gateway/app/api/auth/login/route.ts

57 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 });
}
}