Files
ayris-legal-main/app/api/contact/route.ts
T

153 lines
4.5 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'
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
// Basit in-memory rate limiting
const ipRequestMap = new Map<string, { count: number; resetAt: number }>()
const RATE_LIMIT = 5 // maksimum istek
const WINDOW_MS = 60_000 // 1 dakika
function checkRateLimit(ip: string): boolean {
const now = Date.now()
const entry = ipRequestMap.get(ip)
if (!entry || now > entry.resetAt) {
ipRequestMap.set(ip, { count: 1, resetAt: now + WINDOW_MS })
return true
}
if (entry.count >= RATE_LIMIT) return false
entry.count++
return true
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
async function sendTelegramNotification({
name,
email,
org,
phone,
ip,
}: {
name: string
email: string
org?: string | null
phone?: string | null
ip: string
}) {
const botToken = process.env.TELEGRAM_BOT_TOKEN
const chatId = process.env.TELEGRAM_CHAT_ID
if (!botToken || !chatId) {
console.warn('[AyrisLegal] Telegram bildirim ayarları eksik (TELEGRAM_BOT_TOKEN veya TELEGRAM_CHAT_ID ortam değişkeni tanımlanmamış).')
return
}
const now = new Date().toLocaleString('tr-TR', { timeZone: 'Europe/Istanbul' })
const text =
`⚖️ <b>[AyrisLegal] Yeni Demo & İletişim Talebi</b>\n\n` +
`📍 <b>Kaynak:</b> <code>ayrislegal.com / İletişim Formu</code>\n` +
`👤 <b>Ad Soyad:</b> ${escapeHtml(name)}\n` +
`📧 <b>E-posta:</b> <code>${escapeHtml(email)}</code>\n` +
`🏢 <b>Büro / Kurum:</b> ${org ? escapeHtml(org) : '<i>Belirtilmedi</i>'}\n` +
`📞 <b>Telefon:</b> ${phone ? `<code>${escapeHtml(phone)}</code>` : '<i>Belirtilmedi</i>'}\n` +
`🌐 <b>IP Adresi:</b> <code>${escapeHtml(ip)}</code>\n` +
`⏰ <b>Tarih:</b> ${now}\n\n` +
`<i>Bu mesaj AyrisLegal web sitesinden gönderilmiştir.</i>`
try {
const res = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text,
parse_mode: 'HTML',
disable_web_page_preview: true,
}),
})
if (!res.ok) {
const errText = await res.text()
console.error('[AyrisLegal] Telegram API yanıt hatası:', errText)
} else {
console.log('[AyrisLegal] ✅ Telegram bildirimi başarıyla iletildi.')
}
} catch (error) {
console.error('[AyrisLegal] Telegram gönderim hatası:', error)
}
}
export async function POST(request: NextRequest) {
try {
// IP tespiti
const forwarded = request.headers.get('x-forwarded-for')
const ip = forwarded ? forwarded.split(',')[0].trim() : 'unknown'
// Rate limit
if (!checkRateLimit(ip)) {
return NextResponse.json(
{ success: false, error: 'Çok fazla istek gönderildi. Lütfen bir dakika bekleyip tekrar deneyin.' },
{ status: 429 }
)
}
const body = await request.json()
const { name, email, org, phone, barNo, message, _hp } = body
// Honeypot kontrolü (Bot engelleme)
if (_hp) {
return NextResponse.json({ success: true })
}
// Zorunlu alan doğrulaması
if (!name || typeof name !== 'string' || name.trim().length < 2) {
return NextResponse.json(
{ success: false, error: 'Lütfen ad ve soyadınızı belirtin (en az 2 karakter).' },
{ status: 400 }
)
}
if (!email || typeof email !== 'string' || !EMAIL_REGEX.test(email.trim())) {
return NextResponse.json(
{ success: false, error: 'Lütfen geçerli bir e-posta adresi girin.' },
{ status: 400 }
)
}
const leadData = {
name: name.trim(),
email: email.trim().toLowerCase(),
org: org?.trim() || barNo?.trim() || null,
phone: phone?.trim() || message?.trim() || null,
ip,
}
// Konsol logu
console.log('[AyrisLegal] 🎯 Yeni Demo Talebi Alındı:', {
timestamp: new Date().toISOString(),
...leadData,
})
// Telegram Botuna Anlık Bildirim Gönder (Hata durumunda form akışını kesmez)
await sendTelegramNotification(leadData)
return NextResponse.json({ success: true }, { status: 200 })
} catch (err) {
console.error('[AyrisLegal] Contact API hatası:', err)
return NextResponse.json(
{ success: false, error: 'Sunucu hatası oluştu. Lütfen tekrar deneyin.' },
{ status: 500 }
)
}
}