api key and security
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Flask web server - RSS-Bridge benzeri URL template sistemi
|
||||
"""
|
||||
from flask import Flask, request, Response, jsonify
|
||||
from flask import Flask, request, Response, jsonify, g, after_request
|
||||
from typing import Optional
|
||||
import sys
|
||||
import os
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
@@ -13,10 +15,80 @@ from src.video_fetcher import fetch_videos_from_rss_bridge, get_channel_id_from_
|
||||
from src.transcript_extractor import TranscriptExtractor
|
||||
from src.transcript_cleaner import TranscriptCleaner
|
||||
from src.rss_generator import RSSGenerator
|
||||
from src.security import (
|
||||
init_security, get_security_manager,
|
||||
require_api_key, rate_limit, validate_input
|
||||
)
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Security config yükle
|
||||
_security_config = None
|
||||
def load_security_config():
|
||||
"""Security config'i yükle"""
|
||||
global _security_config
|
||||
if _security_config is None:
|
||||
config_path = Path(__file__).parent.parent / 'config' / 'security.yaml'
|
||||
if config_path.exists():
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
_security_config = yaml.safe_load(f).get('security', {})
|
||||
else:
|
||||
_security_config = {}
|
||||
return _security_config
|
||||
|
||||
# Security manager'ı initialize et
|
||||
def init_app_security():
|
||||
"""Security manager'ı uygulama başlangıcında initialize et"""
|
||||
config = load_security_config()
|
||||
api_keys = config.get('api_keys', {})
|
||||
default_rate_limit = config.get('default_rate_limit', 60)
|
||||
init_security(api_keys, default_rate_limit)
|
||||
|
||||
# Security headers ve CORS middleware
|
||||
@app.after_request
|
||||
def add_security_headers(response):
|
||||
"""Security header'ları ekle"""
|
||||
config = load_security_config()
|
||||
headers = config.get('security_headers', {})
|
||||
|
||||
for header, value in headers.items():
|
||||
response.headers[header] = value
|
||||
|
||||
# CORS headers
|
||||
cors_config = config.get('cors', {})
|
||||
if cors_config.get('enabled', True):
|
||||
origins = cors_config.get('allowed_origins', ['*'])
|
||||
if '*' in origins:
|
||||
response.headers['Access-Control-Allow-Origin'] = '*'
|
||||
else:
|
||||
origin = request.headers.get('Origin')
|
||||
if origin in origins:
|
||||
response.headers['Access-Control-Allow-Origin'] = origin
|
||||
|
||||
response.headers['Access-Control-Allow-Methods'] = ', '.join(
|
||||
cors_config.get('allowed_methods', ['GET', 'OPTIONS'])
|
||||
)
|
||||
response.headers['Access-Control-Allow-Headers'] = ', '.join(
|
||||
cors_config.get('allowed_headers', ['Content-Type', 'X-API-Key'])
|
||||
)
|
||||
|
||||
# Rate limit bilgisini header'a ekle
|
||||
if hasattr(g, 'rate_limit_remaining'):
|
||||
response.headers['X-RateLimit-Remaining'] = str(g.rate_limit_remaining)
|
||||
|
||||
return response
|
||||
|
||||
# OPTIONS handler for CORS
|
||||
@app.route('/', methods=['OPTIONS'])
|
||||
@app.route('/<path:path>', methods=['OPTIONS'])
|
||||
def handle_options(path=None):
|
||||
"""CORS preflight request handler"""
|
||||
return Response(status=200)
|
||||
|
||||
# Uygulama başlangıcında security'yi initialize et
|
||||
init_app_security()
|
||||
|
||||
# Global instances (lazy loading)
|
||||
db = None
|
||||
extractor = None
|
||||
@@ -165,6 +237,8 @@ def process_channel(channel_id: str, max_items: int = 50) -> dict:
|
||||
|
||||
|
||||
@app.route('/', methods=['GET'])
|
||||
@require_api_key # API key zorunlu
|
||||
@validate_input # Input validation
|
||||
def generate_feed():
|
||||
"""
|
||||
RSS-Bridge benzeri URL template:
|
||||
@@ -174,12 +248,15 @@ def generate_feed():
|
||||
- /?channel=@tavakfi&format=Atom
|
||||
- /?channel_url=https://www.youtube.com/@tavakfi&format=Atom
|
||||
"""
|
||||
# Query parametrelerini al
|
||||
# Query parametrelerini al (validate_input decorator zaten sanitize etti)
|
||||
channel_id = request.args.get('channel_id')
|
||||
channel = request.args.get('channel') # @username veya username
|
||||
channel_url = request.args.get('channel_url')
|
||||
format_type = request.args.get('format', 'Atom').lower() # Atom veya Rss
|
||||
max_items = int(request.args.get('max_items', 50))
|
||||
try:
|
||||
max_items = int(request.args.get('max_items', 50))
|
||||
except (ValueError, TypeError):
|
||||
max_items = 50
|
||||
|
||||
# Channel ID'yi normalize et
|
||||
normalized_channel_id = normalize_channel_id(
|
||||
@@ -226,20 +303,26 @@ def generate_feed():
|
||||
generator.add_video_entry(video)
|
||||
|
||||
# Format'a göre döndür
|
||||
response_headers = {}
|
||||
if hasattr(g, 'rate_limit_remaining'):
|
||||
response_headers['X-RateLimit-Remaining'] = str(g.rate_limit_remaining)
|
||||
|
||||
if format_type == 'rss':
|
||||
rss_content = generator.generate_rss_string()
|
||||
response_headers['Content-Type'] = 'application/rss+xml; charset=utf-8'
|
||||
return Response(
|
||||
rss_content,
|
||||
mimetype='application/rss+xml',
|
||||
headers={'Content-Type': 'application/rss+xml; charset=utf-8'}
|
||||
headers=response_headers
|
||||
)
|
||||
else: # Atom
|
||||
# Feedgen Atom desteği
|
||||
atom_content = generator.generate_atom_string()
|
||||
response_headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
|
||||
return Response(
|
||||
atom_content,
|
||||
mimetype='application/atom+xml',
|
||||
headers={'Content-Type': 'application/atom+xml; charset=utf-8'}
|
||||
headers=response_headers
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -250,12 +333,14 @@ def generate_feed():
|
||||
|
||||
|
||||
@app.route('/health', methods=['GET'])
|
||||
@rate_limit(limit_per_minute=120) # Health check için daha yüksek limit
|
||||
def health():
|
||||
"""Health check endpoint"""
|
||||
return jsonify({'status': 'ok', 'service': 'YouTube Transcript RSS Feed'})
|
||||
|
||||
|
||||
@app.route('/info', methods=['GET'])
|
||||
@require_api_key # API key zorunlu
|
||||
def info():
|
||||
"""API bilgileri"""
|
||||
return jsonify({
|
||||
|
||||
Reference in New Issue
Block a user