class Laravel raw sql API Güvenlik Önlemleri extends Post

@created_at( "2025-01-23 05:52" ) @tag( "laravel" )
# ## SQL Injection Koruması SQL injection saldırılarına karşı korunmak için parametreli sorgular kullanın:
// ❌ Güvensiz
$results = DB::select("SELECT * FROM users WHERE id = " . $id);

// ✅ Güvenli - Parametre binding
$results = DB::select("SELECT * FROM users WHERE id = ?", [$id]);
$results = DB::select("SELECT * FROM users WHERE email = :email", ['email' => $email]);
## Input Validasyonu Tüm kullanıcı girdilerini doğrulayın:
public function store(Request $request): JsonResponse 
{
    try {
        $validated = $request->validate([
            'email' => 'required|email|max:255',
            'name' => 'required|string|max:255|regex:/^[a-zA-Z0-9\s]+$/',
            'type' => 'required|in:admin,user,guest',
            'phone' => 'required|regex:/^[0-9]{10}$/'
        ]);
        
        // Validated data ile işlem yap
    } catch (ValidationException $e) {
        return response()->json([
            'message' => 'Validation failed',
            'errors' => $e->errors()
        ], 422);
    }
}
## Rate Limiting API isteklerini sınırlandırın:
// RouteServiceProvider.php
protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });
}

// Route tanımı
Route::middleware(['throttle:60,1'])->group(function () {
    // Dakikada 60 istek ile sınırlı rotalar
});
## Authentication & Authorization
// Middleware
public function handle(Request $request, Closure $next)
{
    if (!auth()->check()) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    if (!auth()->user()->hasPermission('admin')) {
        return response()->json(['error' => 'Forbidden'], 403);
    }

    return $next($request);
}
## CORS Ayarları
// config/cors.php
return [
    'paths' => ['api/*'],
    'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
    'allowed_headers' => ['Content-Type', 'Authorization'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false
];
## Production Güvenlik Kontrol Listesi - [ ] HTTPS zorunlu kılın - [ ] .env dosyasını .gitignore'a ekleyin - [ ] Debug modunu kapatın: `APP_DEBUG=false` - [ ] Composer paketlerini güncelleyin: `composer update` - [ ] Hata mesajlarında detaylı bilgi göstermeyin - [ ] Güçlü API token/JWT kullanın - [ ] File upload kontrolü yapın - [ ] Logları düzenli kontrol edin - [ ] Session/Token timeout süreleri belirleyin - [ ] Kritik işlemler için IP whitelist kullanın ## Hata Yönetimi
try {
    // Kritik işlem
} catch (\Exception $e) {
    Log::error('Hata: ' . $e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => $e->getTraceAsString()
    ]);
    
    return response()->json([
        'message' => 'Bir hata oluştu'  // Kullanıcıya detay vermeyin
    ], 500);
}
## XSS Koruması
// Controller'da
$data = clean($request->input()); // HTML Purifier kullanımı

// Blade template'de
{{ $data }} // Otomatik escape
{!! $data !!} // Raw HTML (dikkatli kullanın)

// JavaScript'te
<script>
    const data = @json($data); // JSON encoding
</script>
## DDoS Koruması - CloudFlare gibi DDoS koruma servisleri kullanın - API Gateway kullanın - Cache mekanizması kurun - Load Balancer kullanın