2026-01-14 20:42:10 +08:00
|
|
|
"""
|
|
|
|
|
Security Service - Handles Turnstile verification, rate limiting, and brute-force protection.
|
|
|
|
|
"""
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
import json
|
2026-04-09 14:30:51 +07:00
|
|
|
import os
|
2026-01-14 20:42:10 +08:00
|
|
|
from datetime import datetime, timedelta
|
2026-04-09 14:30:51 +07:00
|
|
|
from typing import Any, Dict, Tuple
|
|
|
|
|
|
|
|
|
|
import requests
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
from app.utils.db import get_db_connection
|
|
|
|
|
from app.utils.logger import get_logger
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
|
|
# Singleton instance
|
|
|
|
|
_security_service = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_security_service():
|
|
|
|
|
"""Get singleton SecurityService instance"""
|
|
|
|
|
global _security_service
|
|
|
|
|
if _security_service is None:
|
|
|
|
|
_security_service = SecurityService()
|
|
|
|
|
return _security_service
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SecurityService:
|
|
|
|
|
"""Security service for authentication protection"""
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def __init__(self):
|
|
|
|
|
self._load_config()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def _load_config(self):
|
|
|
|
|
"""Load security configuration from environment variables"""
|
|
|
|
|
# Turnstile config
|
2026-04-09 14:30:51 +07:00
|
|
|
self.turnstile_site_key = os.getenv("TURNSTILE_SITE_KEY", "")
|
|
|
|
|
self.turnstile_secret_key = os.getenv("TURNSTILE_SECRET_KEY", "")
|
2026-01-14 20:42:10 +08:00
|
|
|
self.turnstile_enabled = bool(self.turnstile_site_key and self.turnstile_secret_key)
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# IP rate limit config
|
2026-04-09 14:30:51 +07:00
|
|
|
self.ip_max_attempts = int(os.getenv("SECURITY_IP_MAX_ATTEMPTS", "10"))
|
|
|
|
|
self.ip_window_minutes = int(os.getenv("SECURITY_IP_WINDOW_MINUTES", "5"))
|
|
|
|
|
self.ip_block_minutes = int(os.getenv("SECURITY_IP_BLOCK_MINUTES", "15"))
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Account rate limit config
|
2026-04-09 14:30:51 +07:00
|
|
|
self.account_max_attempts = int(os.getenv("SECURITY_ACCOUNT_MAX_ATTEMPTS", "5"))
|
|
|
|
|
self.account_window_minutes = int(os.getenv("SECURITY_ACCOUNT_WINDOW_MINUTES", "60"))
|
|
|
|
|
self.account_block_minutes = int(os.getenv("SECURITY_ACCOUNT_BLOCK_MINUTES", "30"))
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Verification code rate limit
|
2026-04-09 14:30:51 +07:00
|
|
|
self.code_rate_limit_seconds = int(os.getenv("VERIFICATION_CODE_RATE_LIMIT", "60"))
|
|
|
|
|
self.code_ip_hourly_limit = int(os.getenv("VERIFICATION_CODE_IP_HOURLY_LIMIT", "10"))
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def get_security_config(self) -> Dict[str, Any]:
|
|
|
|
|
"""Get public security config for frontend"""
|
|
|
|
|
return {
|
2026-04-09 14:30:51 +07:00
|
|
|
"turnstile_enabled": self.turnstile_enabled,
|
|
|
|
|
"turnstile_site_key": self.turnstile_site_key,
|
|
|
|
|
"registration_enabled": os.getenv("ENABLE_REGISTRATION", "true").lower() == "true",
|
|
|
|
|
"oauth_google_enabled": bool(os.getenv("GOOGLE_CLIENT_ID", "")),
|
|
|
|
|
"oauth_github_enabled": bool(os.getenv("GITHUB_CLIENT_ID", "")),
|
2026-01-14 20:42:10 +08:00
|
|
|
}
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Turnstile Verification
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def verify_turnstile(self, token: str, ip_address: str = None) -> Tuple[bool, str]:
|
|
|
|
|
"""
|
|
|
|
|
Verify Cloudflare Turnstile token.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
(success, message)
|
|
|
|
|
"""
|
|
|
|
|
if not self.turnstile_enabled:
|
|
|
|
|
# If Turnstile is not configured, skip verification
|
2026-04-09 14:30:51 +07:00
|
|
|
return True, "turnstile_disabled"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if not token:
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Missing Turnstile token"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
try:
|
|
|
|
|
response = requests.post(
|
2026-04-09 14:30:51 +07:00
|
|
|
"https://challenges.cloudflare.com/turnstile/v0/siteverify",
|
|
|
|
|
data={"secret": self.turnstile_secret_key, "response": token, "remoteip": ip_address},
|
|
|
|
|
timeout=10,
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
result = response.json()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
|
|
|
|
if result.get("success"):
|
|
|
|
|
return True, "verified"
|
2026-01-14 20:42:10 +08:00
|
|
|
else:
|
2026-04-09 14:30:51 +07:00
|
|
|
error_codes = result.get("error-codes", [])
|
2026-01-14 20:42:10 +08:00
|
|
|
logger.warning(f"Turnstile verification failed: {error_codes}")
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Turnstile verification failed"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
except requests.RequestException as e:
|
|
|
|
|
logger.error(f"Turnstile API error: {e}")
|
|
|
|
|
# On API error, we might want to allow (fail-open) or deny (fail-closed)
|
|
|
|
|
# For security, we'll deny
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Turnstile service unavailable"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Rate Limiting & Brute-Force Protection
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
|
|
|
|
def record_login_attempt(
|
|
|
|
|
self, identifier: str, identifier_type: str, success: bool, ip_address: str = None, user_agent: str = None
|
|
|
|
|
) -> bool:
|
2026-01-14 20:42:10 +08:00
|
|
|
"""
|
|
|
|
|
Record a login attempt for rate limiting.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Args:
|
|
|
|
|
identifier: IP address or username
|
|
|
|
|
identifier_type: 'ip' or 'account'
|
|
|
|
|
success: Whether the attempt was successful
|
|
|
|
|
ip_address: Client IP address
|
|
|
|
|
user_agent: Client user agent string
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
2026-04-09 14:30:51 +07:00
|
|
|
INSERT INTO qd_login_attempts
|
2026-01-14 20:42:10 +08:00
|
|
|
(identifier, identifier_type, success, ip_address, user_agent)
|
|
|
|
|
VALUES (?, ?, ?, ?, ?)
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(identifier, identifier_type, success, ip_address, user_agent),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
db.commit()
|
|
|
|
|
cur.close()
|
|
|
|
|
return True
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to record login attempt: {e}")
|
|
|
|
|
return False
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def is_blocked(self, identifier: str, identifier_type: str) -> Tuple[bool, int]:
|
|
|
|
|
"""
|
|
|
|
|
Check if an identifier (IP or account) is blocked due to too many failed attempts.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
(is_blocked, remaining_seconds)
|
|
|
|
|
"""
|
|
|
|
|
try:
|
2026-04-09 14:30:51 +07:00
|
|
|
if identifier_type == "ip":
|
2026-01-14 20:42:10 +08:00
|
|
|
max_attempts = self.ip_max_attempts
|
|
|
|
|
window_minutes = self.ip_window_minutes
|
|
|
|
|
block_minutes = self.ip_block_minutes
|
|
|
|
|
else: # account
|
|
|
|
|
max_attempts = self.account_max_attempts
|
|
|
|
|
window_minutes = self.account_window_minutes
|
|
|
|
|
block_minutes = self.account_block_minutes
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Count failed attempts in the time window
|
|
|
|
|
window_start = datetime.now() - timedelta(minutes=window_minutes)
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
|
|
|
|
SELECT COUNT(*) as count, MAX(attempt_time) as last_attempt
|
|
|
|
|
FROM qd_login_attempts
|
2026-04-09 14:30:51 +07:00
|
|
|
WHERE identifier = ? AND identifier_type = ?
|
2026-01-14 20:42:10 +08:00
|
|
|
AND success = FALSE AND attempt_time > ?
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(identifier, identifier_type, window_start),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
row = cur.fetchone()
|
|
|
|
|
cur.close()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if not row:
|
|
|
|
|
return False, 0
|
2026-04-09 14:30:51 +07:00
|
|
|
|
|
|
|
|
failed_count = row["count"] or 0
|
|
|
|
|
last_attempt = row["last_attempt"]
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if failed_count >= max_attempts:
|
|
|
|
|
# Check if still in block period
|
|
|
|
|
if last_attempt:
|
|
|
|
|
block_until = last_attempt + timedelta(minutes=block_minutes)
|
|
|
|
|
if datetime.now() < block_until:
|
|
|
|
|
remaining = int((block_until - datetime.now()).total_seconds())
|
|
|
|
|
return True, remaining
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
return False, 0
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to check block status: {e}")
|
|
|
|
|
return False, 0
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def check_login_allowed(self, username: str, ip_address: str) -> Tuple[bool, str]:
|
|
|
|
|
"""
|
|
|
|
|
Check if login is allowed for the given username and IP.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
(allowed, message)
|
|
|
|
|
"""
|
|
|
|
|
# Check IP block
|
2026-04-09 14:30:51 +07:00
|
|
|
ip_blocked, ip_remaining = self.is_blocked(ip_address, "ip")
|
2026-01-14 20:42:10 +08:00
|
|
|
if ip_blocked:
|
|
|
|
|
minutes = ip_remaining // 60
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, f"Too many failed attempts from this IP. Try again in {minutes + 1} minutes."
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Check account block
|
2026-04-09 14:30:51 +07:00
|
|
|
account_blocked, account_remaining = self.is_blocked(username, "account")
|
2026-01-14 20:42:10 +08:00
|
|
|
if account_blocked:
|
|
|
|
|
minutes = account_remaining // 60
|
2026-04-09 14:30:51 +07:00
|
|
|
return (
|
|
|
|
|
False,
|
|
|
|
|
f"Account temporarily locked due to too many failed attempts. Try again in {minutes + 1} minutes.",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return True, "allowed"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def clear_login_attempts(self, identifier: str, identifier_type: str) -> bool:
|
|
|
|
|
"""
|
|
|
|
|
Clear login attempts for an identifier (called after successful login).
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
|
|
|
|
DELETE FROM qd_login_attempts
|
|
|
|
|
WHERE identifier = ? AND identifier_type = ?
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(identifier, identifier_type),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
db.commit()
|
|
|
|
|
cur.close()
|
|
|
|
|
return True
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to clear login attempts: {e}")
|
|
|
|
|
return False
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Security Audit Logging
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
|
|
|
|
def log_security_event(
|
|
|
|
|
self, action: str, user_id: int = None, ip_address: str = None, user_agent: str = None, details: dict = None
|
|
|
|
|
) -> bool:
|
2026-01-14 20:42:10 +08:00
|
|
|
"""
|
|
|
|
|
Log a security-related event.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Args:
|
|
|
|
|
action: Event type (login, logout, register, reset_password, etc.)
|
|
|
|
|
user_id: User ID if applicable
|
|
|
|
|
ip_address: Client IP
|
|
|
|
|
user_agent: Client user agent
|
|
|
|
|
details: Additional details as dict
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
details_json = json.dumps(details) if details else None
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
2026-04-09 14:30:51 +07:00
|
|
|
INSERT INTO qd_security_logs
|
2026-01-14 20:42:10 +08:00
|
|
|
(user_id, action, ip_address, user_agent, details)
|
|
|
|
|
VALUES (?, ?, ?, ?, ?)
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(user_id, action, ip_address, user_agent, details_json),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
db.commit()
|
|
|
|
|
cur.close()
|
|
|
|
|
return True
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to log security event: {e}")
|
|
|
|
|
return False
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Verification Code Rate Limiting
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def can_send_verification_code(self, email: str, ip_address: str) -> Tuple[bool, str]:
|
|
|
|
|
"""
|
|
|
|
|
Check if we can send a verification code to this email from this IP.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
(allowed, message)
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Check email rate limit (one code per minute per email)
|
|
|
|
|
rate_limit_time = datetime.now() - timedelta(seconds=self.code_rate_limit_seconds)
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
|
|
|
|
SELECT COUNT(*) as count FROM qd_verification_codes
|
|
|
|
|
WHERE email = ? AND created_at > ?
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(email, rate_limit_time),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
row = cur.fetchone()
|
2026-04-09 14:30:51 +07:00
|
|
|
if row and row["count"] > 0:
|
|
|
|
|
return False, f"Please wait {self.code_rate_limit_seconds} seconds before requesting another code"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Check IP hourly limit
|
|
|
|
|
hour_ago = datetime.now() - timedelta(hours=1)
|
|
|
|
|
cur.execute(
|
|
|
|
|
"""
|
|
|
|
|
SELECT COUNT(*) as count FROM qd_verification_codes
|
|
|
|
|
WHERE ip_address = ? AND created_at > ?
|
|
|
|
|
""",
|
2026-04-09 14:30:51 +07:00
|
|
|
(ip_address, hour_ago),
|
2026-01-14 20:42:10 +08:00
|
|
|
)
|
|
|
|
|
row = cur.fetchone()
|
2026-04-09 14:30:51 +07:00
|
|
|
if row and row["count"] >= self.code_ip_hourly_limit:
|
|
|
|
|
return False, "Too many verification code requests from this IP. Try again later."
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
cur.close()
|
2026-04-09 14:30:51 +07:00
|
|
|
return True, "allowed"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to check verification code rate limit: {e}")
|
2026-04-09 14:30:51 +07:00
|
|
|
return True, "allowed" # Fail open on DB errors
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Password Strength Validation
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def validate_password_strength(self, password: str) -> Tuple[bool, str]:
|
|
|
|
|
"""
|
|
|
|
|
Validate password meets minimum security requirements.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Requirements:
|
|
|
|
|
- At least 8 characters
|
|
|
|
|
- Contains at least one uppercase letter
|
|
|
|
|
- Contains at least one lowercase letter
|
|
|
|
|
- Contains at least one digit
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
(valid, message)
|
|
|
|
|
"""
|
|
|
|
|
if len(password) < 8:
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Password must be at least 8 characters long"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if not any(c.isupper() for c in password):
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Password must contain at least one uppercase letter"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if not any(c.islower() for c in password):
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Password must contain at least one lowercase letter"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
if not any(c.isdigit() for c in password):
|
2026-04-09 14:30:51 +07:00
|
|
|
return False, "Password must contain at least one digit"
|
|
|
|
|
|
|
|
|
|
return True, "valid"
|
|
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# =========================================================================
|
|
|
|
|
# Cleanup
|
|
|
|
|
# =========================================================================
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
def cleanup_old_records(self, days: int = 7) -> int:
|
|
|
|
|
"""
|
|
|
|
|
Clean up old login attempts and expired verification codes.
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
Returns:
|
|
|
|
|
Number of records deleted
|
|
|
|
|
"""
|
|
|
|
|
deleted = 0
|
|
|
|
|
cutoff = datetime.now() - timedelta(days=days)
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
try:
|
|
|
|
|
with get_db_connection() as db:
|
|
|
|
|
cur = db.cursor()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Clean old login attempts
|
2026-04-09 14:30:51 +07:00
|
|
|
cur.execute("DELETE FROM qd_login_attempts WHERE attempt_time < ?", (cutoff,))
|
2026-01-14 20:42:10 +08:00
|
|
|
deleted += cur.rowcount or 0
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
# Clean expired verification codes
|
2026-04-09 14:30:51 +07:00
|
|
|
cur.execute("DELETE FROM qd_verification_codes WHERE expires_at < ?", (cutoff,))
|
2026-01-14 20:42:10 +08:00
|
|
|
deleted += cur.rowcount or 0
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
db.commit()
|
|
|
|
|
cur.close()
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
logger.info(f"Security cleanup: deleted {deleted} old records")
|
|
|
|
|
return deleted
|
2026-04-09 14:30:51 +07:00
|
|
|
|
2026-01-14 20:42:10 +08:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Security cleanup failed: {e}")
|
|
|
|
|
return 0
|