handwrit / core /security.py
yaminXwin's picture
Upload 49 files
2c1e073 verified
Raw History Blame Contribute Delete
3.5 kB
"""
Security, Rate Limiting & Access Control Module.
Enforces:
- In-memory sliding window rate limiting per IP / client ID
- Request validation & payload size caps
- Pro license verification for protected features
- Watermark burning for free-tier image & PDF generation
"""
import time
from typing import Dict, List, Optional
from fastapi import Request, HTTPException, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from core.payments import verify_license_token
security_scheme = HTTPBearer(auto_error=False)
# Simple sliding window rate limiter
RATE_LIMIT_STORE: Dict[str, List[float]] = {}
MAX_REQUESTS_PER_MINUTE_FREE = 15
MAX_REQUESTS_PER_MINUTE_PRO = 120
def check_rate_limit(client_ip: str, is_pro: bool = False) -> bool:
"""
Returns True if request is within allowed rate limits, False otherwise.
Prunes expired entries to prevent memory leaks in production.
"""
now = time.time()
window_start = now - 60.0
limit = MAX_REQUESTS_PER_MINUTE_PRO if is_pro else MAX_REQUESTS_PER_MINUTE_FREE
# Periodic cleanup if store grows large
if len(RATE_LIMIT_STORE) > 5000:
stale_keys = [k for k, ts in RATE_LIMIT_STORE.items() if not ts or ts[-1] <= window_start]
for k in stale_keys:
RATE_LIMIT_STORE.pop(k, None)
timestamps = RATE_LIMIT_STORE.get(client_ip, [])
# Filter out timestamps older than 60 seconds
timestamps = [t for t in timestamps if t > window_start]
if len(timestamps) >= limit:
RATE_LIMIT_STORE[client_ip] = timestamps
return False
timestamps.append(now)
RATE_LIMIT_STORE[client_ip] = timestamps
return True
def get_current_user_license(credentials: Optional[HTTPAuthorizationCredentials] = Security(security_scheme)) -> Optional[dict]:
"""
Extracts and validates the bearer token if provided. Returns license payload or None.
"""
if not credentials or not credentials.credentials:
return None
token = credentials.credentials
return verify_license_token(token)
def burn_watermark_on_pil_image(image: Image.Image, text: str = "EURION HANDWRITING — FREE PREVIEW") -> Image.Image:
"""
Indelibly stamps a prominent semi-transparent diagonal watermark across the page for free exports.
"""
img = image.convert("RGBA")
txt_overlay = Image.new("RGBA", img.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(txt_overlay)
w, h = img.size
# Try to load a font or fallback to default
try:
font = ImageFont.truetype("arial.ttf", int(h * 0.035))
except Exception:
font = ImageFont.load_default()
# Draw diagonal lines with watermark text
for y_offset in range(int(h * 0.15), int(h * 0.9), int(h * 0.22)):
draw.text(
(int(w * 0.08), y_offset),
text,
fill=(180, 20, 20, 75), # Semi-transparent red/gray stamp
font=font
)
# Bottom banner
draw.rectangle([0, h - 45, w, h], fill=(20, 20, 20, 160))
try:
small_font = ImageFont.truetype("arial.ttf", 20)
except Exception:
small_font = ImageFont.load_default()
draw.text((w // 2 - 220, h - 35), "Generated via Eurion Studio — Upgrade to remove watermark", fill=(255, 255, 255, 230), font=small_font)
# Composite together
watermarked = Image.alpha_composite(img, txt_overlay)
return watermarked.convert("RGB")