Files
next-go-blog/docs/SETTINGS_API.md
Beyhan Oğur 6d95e27114 first commit
2026-04-26 22:16:43 +03:00

12 KiB
Raw Permalink Blame History

🔧 CORS & Rate Limit Yönetim API'si

Yeni Endpoint'ler

Base URL

http://localhost:8080/v1/settings

Not: Tüm settings endpoint'leri authentication gerektirir (Bearer token).


📋 CORS Whitelist Yönetimi

1. Tüm Whitelist Kayıtlarını Getir

GET /v1/settings/cors/whitelist
Authorization: Bearer {token}

Response:

[
  {
    "id": "uuid",
    "origin": "http://localhost:3000",
    "description": "Default local frontend",
    "is_active": true,
    "created_by": "system",
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T00:00:00Z"
  }
]

2. Yeni Whitelist Ekle

POST /v1/settings/cors/whitelist
Authorization: Bearer {token}
Content-Type: application/json

Request Body:

{
  "origin": "https://example.com",
  "description": "Production frontend"
}

Response (201):

{
  "id": "uuid",
  "origin": "https://example.com",
  "description": "Production frontend",
  "is_active": true,
  "created_by": "user@example.com",
  "created_at": "2026-02-04T00:00:00Z",
  "updated_at": "2026-02-04T00:00:00Z"
}

3. Whitelist Güncelle

PUT /v1/settings/cors/whitelist/{id}
Authorization: Bearer {token}
Content-Type: application/json

Request Body:

{
  "origin": "https://newdomain.com",
  "description": "Updated description",
  "is_active": false
}

Response (200):

{
  "message": "Whitelist updated successfully"
}

4. Whitelist Sil

DELETE /v1/settings/cors/whitelist/{id}
Authorization: Bearer {token}

Response (200):

{
  "message": "Whitelist entry deleted successfully"
}

🚫 CORS Blacklist Yönetimi

1. Tüm Blacklist Kayıtlarını Getir

GET /v1/settings/cors/blacklist
Authorization: Bearer {token}

Response:

[
  {
    "id": "uuid",
    "origin": "http://malicious-site.com",
    "reason": "Security threat",
    "is_active": true,
    "created_by": "admin@example.com",
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T00:00:00Z"
  }
]

2. Yeni Blacklist Ekle

POST /v1/settings/cors/blacklist
Authorization: Bearer {token}
Content-Type: application/json

Request Body:

{
  "origin": "http://spam-site.com",
  "reason": "Spam attempts detected"
}

Response (201):

{
  "id": "uuid",
  "origin": "http://spam-site.com",
  "reason": "Spam attempts detected",
  "is_active": true,
  "created_by": "user@example.com",
  "created_at": "2026-02-04T00:00:00Z",
  "updated_at": "2026-02-04T00:00:00Z"
}

3. Blacklist Güncelle

PUT /v1/settings/cors/blacklist/{id}
Authorization: Bearer {token}
Content-Type: application/json

Request Body:

{
  "origin": "http://updated-domain.com",
  "reason": "Updated reason",
  "is_active": true
}

Response (200):

{
  "message": "Blacklist updated successfully"
}

4. Blacklist Sil

DELETE /v1/settings/cors/blacklist/{id}
Authorization: Bearer {token}

Response (200):

{
  "message": "Blacklist entry deleted successfully"
}

Rate Limit Ayarları Yönetimi

1. Tüm Rate Limit Ayarlarını Getir

GET /v1/settings/ratelimit
Authorization: Bearer {token}

Response:

[
  {
    "id": "uuid",
    "name": "login",
    "description": "Login endpoint rate limit",
    "max_requests": 5,
    "window_seconds": 60,
    "is_active": true,
    "updated_by": "admin@example.com",
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T00:00:00Z"
  },
  {
    "id": "uuid",
    "name": "register",
    "description": "Registration endpoint rate limit",
    "max_requests": 3,
    "window_seconds": 300,
    "is_active": true,
    "updated_by": null,
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T00:00:00Z"
  },
  {
    "id": "uuid",
    "name": "api",
    "description": "General API rate limit",
    "max_requests": 100,
    "window_seconds": 60,
    "is_active": true,
    "updated_by": null,
    "created_at": "2026-02-04T00:00:00Z",
    "updated_at": "2026-02-04T00:00:00Z"
  }
]

2. Rate Limit Ayarını Güncelle

PUT /v1/settings/ratelimit/{id}
Authorization: Bearer {token}
Content-Type: application/json

Request Body:

{
  "max_requests": 10,
  "window_seconds": 120,
  "description": "Updated rate limit",
  "is_active": true
}

Response (200):

{
  "message": "Rate limit setting updated successfully"
}

🔄 Çalışma Mantığı

CORS Kontrolü

  1. Request gelir → Origin header okunur
  2. Blacklist kontrolü → Origin blacklist'te var mı?
    • Varsa → 403 Forbidden
  3. Whitelist kontrolü → Origin whitelist'te var mı?
    • Varsa → İzin ver
    • Yoksa → 403 Forbidden

Cache Stratejisi

  • Whitelist/Blacklist: 1 saat cache
  • Rate Limit Settings: 1 saat cache
  • Her CRUD işleminden sonra ilgili cache invalidate edilir
  • Database'den tekrar okunur ve cache'lenir

Rate Limiting

  1. Database'den ayarlar okunur (cache'den veya DB'den)
  2. IP bazlı sayaç Redis'te tutulur
  3. Limit aşılırsa429 Too Many Requests

📝 Kullanım Örnekleri

JavaScript/TypeScript

const API_BASE = 'http://localhost:8080/v1/settings';
const token = localStorage.getItem('access_token');

// Whitelist'e yeni origin ekle
async function addToWhitelist(origin, description) {
  const response = await fetch(`${API_BASE}/cors/whitelist`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ origin, description })
  });
  
  return response.json();
}

// Rate limit ayarlarını getir
async function getRateLimits() {
  const response = await fetch(`${API_BASE}/ratelimit`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });
  
  return response.json();
}

// Rate limit güncelle
async function updateRateLimit(id, maxRequests, windowSeconds) {
  const response = await fetch(`${API_BASE}/ratelimit/${id}`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      max_requests: maxRequests,
      window_seconds: windowSeconds
    })
  });
  
  return response.json();
}

// Blacklist'e ekle
async function addToBlacklist(origin, reason) {
  const response = await fetch(`${API_BASE}/cors/blacklist`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ origin, reason })
  });
  
  return response.json();
}

cURL Örnekleri

# Token al (önce login)
TOKEN="your_access_token_here"

# Whitelist'i görüntüle
curl -X GET http://localhost:8080/v1/settings/cors/whitelist \
  -H "Authorization: Bearer $TOKEN"

# Yeni origin ekle
curl -X POST http://localhost:8080/v1/settings/cors/whitelist \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "origin": "https://myapp.com",
    "description": "Production app"
  }'

# Whitelist güncelle
curl -X PUT http://localhost:8080/v1/settings/cors/whitelist/UUID_HERE \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": false
  }'

# Blacklist'e ekle
curl -X POST http://localhost:8080/v1/settings/cors/blacklist \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "origin": "http://bad-site.com",
    "reason": "Security threat"
  }'

# Rate limit ayarlarını görüntüle
curl -X GET http://localhost:8080/v1/settings/ratelimit \
  -H "Authorization: Bearer $TOKEN"

# Rate limit güncelle
curl -X PUT http://localhost:8080/v1/settings/ratelimit/UUID_HERE \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "max_requests": 20,
    "window_seconds": 60,
    "description": "Updated login limit"
  }'

🗄️ Database Tabloları

cors_whitelists

CREATE TABLE cors_whitelists (
    id UUID PRIMARY KEY,
    origin VARCHAR(255) UNIQUE NOT NULL,
    description TEXT,
    is_active BOOLEAN DEFAULT true,
    created_by VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

cors_blacklists

CREATE TABLE cors_blacklists (
    id UUID PRIMARY KEY,
    origin VARCHAR(255) UNIQUE NOT NULL,
    reason TEXT,
    is_active BOOLEAN DEFAULT true,
    created_by VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

rate_limit_settings

CREATE TABLE rate_limit_settings (
    id UUID PRIMARY KEY,
    name VARCHAR(100) UNIQUE NOT NULL,
    description TEXT,
    max_requests BIGINT NOT NULL,
    window_seconds INTEGER NOT NULL,
    is_active BOOLEAN DEFAULT true,
    updated_by VARCHAR(255),
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);

⚙️ Default Ayarlar

Uygulama ilk kez başlatıldığında otomatik olarak şu ayarlar oluşturulur:

CORS Whitelist

  • http://localhost:3000 - Default local frontend
  • http://localhost:8080 - Backend self

Rate Limit Settings

  • login: 5 istek / 60 saniye
  • register: 3 istek / 300 saniye
  • api: 100 istek / 60 saniye

🔐 Güvenlik Notları

  1. Authentication Zorunlu: Tüm settings endpoint'leri authentication gerektirir
  2. Admin Kontrolü: Şu anda tüm authenticated kullanıcılar yönetebilir (TODO: Admin role check eklenecek)
  3. Cache: Değişiklikler 1 saat boyunca cache'de kalır
  4. Blacklist Önceliği: Blacklist kontrolü whitelist'ten önce yapılır

📊 Frontend Admin Panel Örneği

// Admin Panel Component
class CorsManagement {
  constructor() {
    this.api = 'http://localhost:8080/v1/settings';
    this.token = localStorage.getItem('access_token');
  }

  async getWhitelist() {
    const res = await fetch(`${this.api}/cors/whitelist`, {
      headers: { 'Authorization': `Bearer ${this.token}` }
    });
    return res.json();
  }

  async addWhitelist(origin, description) {
    const res = await fetch(`${this.api}/cors/whitelist`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ origin, description })
    });
    return res.json();
  }

  async updateWhitelist(id, data) {
    const res = await fetch(`${this.api}/cors/whitelist/${id}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    return res.json();
  }

  async deleteWhitelist(id) {
    const res = await fetch(`${this.api}/cors/whitelist/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${this.token}` }
    });
    return res.json();
  }
}

// Kullanım
const corsManager = new CorsManagement();

// Whitelist listele
corsManager.getWhitelist().then(data => {
  console.log('Whitelist:', data);
});

// Yeni ekle
corsManager.addWhitelist('https://myapp.com', 'Production app');

// Güncelle
corsManager.updateWhitelist('uuid-here', { is_active: false });

// Sil
corsManager.deleteWhitelist('uuid-here');

Özet

Artık CORS whitelist/blacklist ve rate limit ayarlarını:

  • Database'de saklayabiliyorsunuz
  • Redis ile cache'leyebiliyorsunuz
  • Frontend'den yönetebiliyorsunuz
  • CRUD işlemleri yapabiliyorsunuz
  • Dinamik olarak güncelleyebiliyorsunuz

Tüm ayarlar database'de tutulur, değişiklikler anında Redis cache'ini invalidate eder ve yeni değerler kullanılmaya başlanır!