Files
gulermak_metro/app/api/auth/login/route.ts
Şahan Hasret 76c31274d5 Database
2025-11-21 17:46:30 +03:00

74 lines
1.7 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 { NextRequest, NextResponse } from 'next/server';
import { compare } from 'bcryptjs';
import { prisma } from '@/lib/prisma';
import { encrypt } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
const { username, password } = await request.json();
if (!username || !password) {
return NextResponse.json(
{ error: 'Kullanıcı adı ve şifre gerekli' },
{ status: 400 }
);
}
// Kullanıcıyı bul
const user = await prisma.user.findUnique({
where: { username },
});
if (!user) {
return NextResponse.json(
{ error: 'Kullanıcı adı veya şifre hatalı' },
{ status: 401 }
);
}
// Şifreyi kontrol et
const isPasswordValid = await compare(password, user.password);
if (!isPasswordValid) {
return NextResponse.json(
{ error: 'Kullanıcı adı veya şifre hatalı' },
{ status: 401 }
);
}
// JWT token oluştur
const token = await encrypt({
userId: user.id.toString(),
username: user.username,
});
// Response oluştur
const response = NextResponse.json(
{
user: {
id: user.id,
username: user.username,
},
},
{ status: 200 }
);
// Cookie'ye token ekle
response.cookies.set('session', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24, // 24 saat
path: '/',
});
return response;
} catch (error) {
console.error('Login error:', error);
return NextResponse.json(
{ error: 'Giriş yapılırken bir hata oluştu' },
{ status: 500 }
);
}
}