Spaces:
Running on Zero
Running on Zero
Commit ·
359aa35
1
Parent(s): e00358c
Deploy audited SahihIslam SuperAdmin backend
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.development.exampleAdded+67
- .env.exampleAdded+267
- .env.production.exampleAdded+69
- .env.staging.exampleAdded+64
- .gitattributesAdded+1
- .gitignoreAdded+104
- R2_INTEGRATION_SUMMARY.mdAdded+295
- README.mdAdded+53
- README_APP.mdAdded+50
- README_SUPERADMIN.mdAdded+53
- RELEASE_VERSIONAdded+1
- app.pyAdded+488
- app/__init__.pyAdded+1
- app/ads_routes.pyAdded+1906
- app/api/__init__.pyAdded
- app/api/contact.pyAdded+168
- app/api/razorpay_standard.pyAdded+1161
- app/api/v1/__init__.pyAdded+14
- app/api/v1/prayer.pyAdded+124
- app/api/v1/quran.pyAdded+33
- app/auth.pyAdded
- app/auth_deps.pyAdded+806
- app/content_moderation.pyAdded+599
- app/core/__init__.pyAdded
- app/core/app_release.pyAdded+101
- app/core/config.pyAdded+771
- app/core/media_token.pyAdded+160
- app/core/rate_limits.pyAdded+324
- app/core/runtime_settings.pyAdded+612
- app/core/security.pyAdded+154
- app/crypto_security.pyAdded+18
- app/database.pyAdded+4
- app/events_routes.pyAdded+1038
- app/geocoding.pyAdded+10
- app/hadith.pyAdded
- app/hijri.pyAdded+188
- app/inference_client.pyAdded+13
- app/infrastructure/__init__.pyAdded
- app/infrastructure/database.pyAdded+6
- app/infrastructure/firebase.pyAdded+242
- app/infrastructure/mongodb.pyAdded+1511
- app/infrastructure/redis.pyAdded+576
- app/infrastructure/storage.pyAdded+823
- app/intent_router.pklAdded
- app/limiter.pyAdded+9
- app/main.pyAdded+7
- app/masjid_routes.pyAdded
- app/models.pyAdded+951
- app/money.pyAdded+207
- app/mufti_routes.pyAdded+357
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# ==============================================================================# SAHIH ISLAM ENTERPRISE - DEVELOPMENT ENVIRONMENT CONFIGURATION (.env.development)# ==============================================================================# Architecture Profile: Local Development & Unit/Integration Testing# Databases: Isolated to `sahihislam_dev`, `sahihislam_dev_admin`, `sahihislam_dev_commerce`# NEVER use production secrets or target production databases in development!# ==============================================================================
# Application Environment TierAPP_ENV=developmentPORT=7860
# Database Configuration (MongoDB)# Local instance or dedicated development Atlas clusterMONGO_URI=mongodb://localhost:27017/sahihislam_devMONGO_DB_NAME=sahihislam_devMONGO_DB_ADMIN_NAME=sahihislam_dev_adminMONGO_DB_COMMERCE_NAME=sahihislam_dev_commerceMONGO_MAX_POOL_SIZE=10MONGO_MIN_POOL_SIZE=2MONGO_WAIT_QUEUE_TIMEOUT_MS=5000
# Cache & Distributed Rate Limiting (Redis)# Leave empty to use in-memory fallback cache during local developmentREDIS_URL=ENABLE_RATE_LIMIT=1ENABLE_REDIS_RATE_LIMIT=0
# Security & Staff Master Key# In development, the default development key is permitted for convenienceSECRET_KEY=sahihislam_enterprise_superadmin_master_secret_2026STAFF_SECRET_KEY=sahihislam_enterprise_superadmin_master_secret_2026
# CORS Allowed Origins# Permits local Flutter Web and frontend test harnessesALLOWED_ORIGINS=http://localhost:7860,http://localhost:8080,http://localhost:3000,http://127.0.0.1:7860,http://127.0.0.1:8080,http://127.0.0.1:3000
# Proxy & Network IsolationTRUSTED_PROXY_COUNT=0TRUSTED_PROXY_HOSTS=*
# Firebase Authentication & Admin SDK# Development sandbox project IDFIREBASE_PROJECT_ID=sahih-islam-dev# Path to local development service account key JSON or leave empty for local emulationFIREBASE_ADMIN_CREDENTIALS=firebase_credentials.dev.json
# Google Play In-App Billing (Testing Sandbox)GOOGLE_PLAY_PACKAGE_NAME=com.sahihislam.appGOOGLE_PLAY_SERVICE_ACCOUNT_KEY=
# Cloudflare R2 Storage (Edge Audio & Assets)CLOUDFLARE_ACCOUNT_ID=d7fc285dc6825480f6d8c887f93e7084R2_ACCESS_KEY_ID=dev_placeholder_key_idR2_SECRET_ACCESS_KEY=dev_placeholder_secret_keyR2_BUCKET_NAME=sahihislam-devR2_PUBLIC_DOMAIN=https://dev-cdn.sahihislam.comCF_WORKER_URL=http://localhost:8787
# LLM Providers (Hadith & Quran Multi-lingual AI)DEEPSEEK_API_KEY=XAI_API_KEY=OPENROUTER_API_KEY=ML_CONCURRENCY=2
# ObservabilityLOG_LEVEL=DEBUG123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267# ==============================================================================# SAHIH ISLAM ENTERPRISE - CENTRALIZED CONFIGURATION SCHEMA (.env.example)# ==============================================================================# This sanitized template documents every service, credential, and parameter# required by the Sahih Islam platform across development, staging, and production.## COPY this file to .env and provide your deployment-specific values.# NEVER commit .env to version control or public repositories!# ==============================================================================
# ==============================================================================# 1. APPLICATION & SERVER ENVIRONMENT# ==============================================================================# Runtime environment: development, staging, or productionAPP_ENV=development
# Web server socket bindingsWEB_HOST=0.0.0.0PORT=7860WEB_PORT=7860
# Concurrency workers (1 for local development; 2-4 in production with Gunicorn)WEB_WORKERS=1
# Log verbosity: DEBUG, INFO, WARNING, ERROR, CRITICALLOG_LEVEL=INFO
# ==============================================================================# 2. CORE SECURITY & ACCESS CONTROL# ==============================================================================# Master cryptographic secret for session signing, staff tokens, and HMAC hashes.# In PRODUCTION, this MUST be a high-entropy string of at least 32 characters.SECRET_KEY=change_me_to_a_cryptographically_secure_random_string_min_32_charsSTAFF_SECRET_KEY=change_me_to_a_cryptographically_secure_random_string_min_32_charsJWT_SECRET=change_me_to_a_cryptographically_secure_random_string_min_32_chars
# Comma-separated list of authorized SuperAdmin email addressesSUPERADMIN_EMAILS=admin@sahihislam.org,support@sahihislam.org
# Optional bootstrap Firebase UID with automatic superadmin promotionBOOTSTRAP_ADMIN_UID=
# CORS Allowed Origins (Comma-separated list of trusted web origins)# Development default includes local Flutter, React, and Vite ports.# PRODUCTION: Must be explicitly set to your actual domain(s), e.g. https://sahih-islam-app.web.appALLOWED_ORIGINS=http://localhost:8080,http://localhost:3000,http://localhost:7860,https://sahih-islam-app.web.app
# Trusted Reverse Proxy Count and IP Allowlist (Anti-Spoofing Guard)# Behind Cloudflare / Traefik / ALB, set count to 1+.TRUSTED_PROXY_COUNT=1TRUSTED_PROXY_HOSTS=127.0.0.1,::1
# ==============================================================================# 3. MONGODB DATABASE (ATLAS / SELF-HOSTED)# ==============================================================================# MongoDB Connection URI (Accepts both MONGODB_URI and legacy MONGO_URI)# Development: mongodb://localhost:27017/sahihislam_dev# Production: mongodb+srv://<username>:<password>@cluster.mongodb.net/sahihislam?retryWrites=true&w=majorityMONGODB_URI=mongodb://localhost:27017/sahihislam_devMONGO_URI=mongodb://localhost:27017/sahihislam_dev
# Database namespace isolationMONGODB_DB_NAME=sahihislam_devMONGO_DB_NAME=sahihislam_devMONGO_DB_ADMIN_NAME=sahihislam_dev_adminMONGO_DB_COMMERCE_NAME=sahihislam_dev_commerce
# Enterprise Connection Pool Sizing (Tuned for Atlas M0 / Dedicated tiers)MONGODB_MAX_POOL_SIZE=50MONGODB_MIN_POOL_SIZE=5MONGODB_WAIT_QUEUE_TIMEOUT_MS=5000
# Safety Guard: Set to 1 ONLY if intentionally connecting a dev server to production DBALLOW_DEV_PROD_DB_CONNECT=0
# ==============================================================================# 4. REDIS CACHING & DISTRIBUTED RATE LIMITING# ==============================================================================# Connection URL (Supports TLS via rediss:// for Upstash / Redis Cloud)# If left empty, backend automatically operates in high-performance in-memory cache mode.REDIS_URL=redis://localhost:6379/0
# Granular Redis connection parameters (Used if REDIS_URL is not set)REDIS_HOST=localhostREDIS_PORT=6379REDIS_PASSWORD=REDIS_DB=0
# Rate Limiter Feature FlagsENABLE_RATE_LIMIT=trueENABLE_REDIS_RATE_LIMIT=false
# ==============================================================================# 5. FIREBASE (AUTHENTICATION & ADMIN SDK)# ==============================================================================# Firebase Project IDFIREBASE_PROJECT_ID=sahih-islam-app
# Server-Side Admin SDK Credentials# Option A: Absolute or relative file path to service account JSONFIREBASE_ADMIN_CREDENTIALS=firebase_credentials.json
# Option B: Raw JSON string or Base64-encoded JSON (Ideal for Cloud Run / HF Spaces)FIREBASE_JSON_STRING=
# Firebase Web API Key (Used strictly for server-side auth token minting / tests)FIREBASE_WEB_API_KEY=your_firebase_web_api_key_here
# ==============================================================================# 6. GOOGLE PLAY CONSOLE & IN-APP PURCHASES (IAP)# ==============================================================================# Official Android package identifierGOOGLE_PLAY_PACKAGE_NAME=com.sahihislam.app
# Google Play Developer API Service Account (androidpublisher scope)# Option A: File path to Google service account credentials JSONGOOGLE_PLAY_SERVICE_ACCOUNT_JSON=firebase_credentials.json
# Option B: Raw JSON string of Google service account credentialsGOOGLE_PLAY_SERVICE_ACCOUNT_RAW=
# Option C: Keyless Authentication (GCP Workload Identity / ADC)# If running on GCP with Google Play publisher IAM role, no key is needed.
# Real-Time Developer Notifications (RTDN) Webhook SecretGOOGLE_PLAY_WEBHOOK_SECRET=your_google_play_rtdn_webhook_secret_here
# Allow simulated test receipts in non-production environmentsALLOW_MOCK_GOOGLE_PLAY=1
# ==============================================================================# 7. RAZORPAY PAYMENT GATEWAY (WEB & MOBILE UPI/CARDS)# ==============================================================================# Razorpay Key ID (Test prefix: rzp_test_..., Production prefix: rzp_live_...)RAZORPAY_KEY_ID=your_razorpay_key_id_here
# Razorpay Key Secret (Server-side ONLY; NEVER expose to client)RAZORPAY_KEY_SECRET=your_razorpay_key_secret_here
# Razorpay Webhook Signature SecretRAZORPAY_WEBHOOK_SECRET=your_razorpay_webhook_secret_here
# ==============================================================================# 8. APPLE STOREKIT & APP STORE SERVER API (iOS)# ==============================================================================APPLE_KEY_ID=your_apple_key_idAPPLE_ISSUER_ID=your_apple_issuer_uuidAPPLE_PRIVATE_KEY=APPLE_PRIVATE_KEY_PATH=APPLE_BUNDLE_ID=com.sahihislam.appAPPLE_ENVIRONMENT=sandbox# Options: sandbox (development/testing), production
# ==============================================================================# 9. CLOUDFLARE (R2 STORAGE & WORKER EDGE PROXY)# ==============================================================================# Cloudflare Account ID (Found in Cloudflare Dashboard URL)CLOUDFLARE_ACCOUNT_ID=your_cloudflare_account_id_hereR2_ACCOUNT_ID=your_cloudflare_account_id_here
# R2 S3-Compatible API CredentialsCLOUDFLARE_R2_ACCESS_KEY_ID=your_r2_access_key_id_hereR2_ACCESS_KEY_ID=your_r2_access_key_id_here
CLOUDFLARE_R2_SECRET_ACCESS_KEY=your_r2_secret_access_key_hereR2_SECRET_ACCESS_KEY=your_r2_secret_access_key_here
# Storage Bucket NameCLOUDFLARE_R2_BUCKET_NAME=sahihislamR2_BUCKET_NAME=sahihislam
# Optional Public CDN Custom Domain for R2 BucketCLOUDFLARE_R2_PUBLIC_DOMAIN=https://media.sahihislam.orgR2_PUBLIC_DOMAIN=https://media.sahihislam.org
# Cloudflare Edge Worker URLCLOUDFLARE_WORKER_URL=https://api-proxy.sahihislamapp.workers.devCF_WORKER_URL=https://api-proxy.sahihislamapp.workers.dev
# Edge Worker Direct Upload Shared SecretCLOUDFLARE_WORKER_SECRET=your_worker_upload_secret_hereCF_WORKER_SECRET=your_worker_upload_secret_here
# Cloudflare API Token (For DNS / Worker automation)CLOUDFLARE_API_TOKEN=your_cloudflare_api_token_here
# ==============================================================================# 10. HUGGING FACE & EMBEDDINGS ACCELERATION# ==============================================================================# Hugging Face Access Token (For gated ONNX models, BGE-M3, and rerankers)HUGGINGFACE_TOKEN=your_huggingface_token_hereHF_TOKEN=your_huggingface_token_here
# ==============================================================================# 11. GOOGLE ADMOB & AADS FRAUD SHIELD# ==============================================================================# AdMob mode: 'test' (safe test ads) or 'production' (live monetization)ADMOB_MODE=test
# Optional AdMob Test Device ID (hash from logcat on physical test device)ADMOB_TEST_DEVICE_ID=
# AADS Publisher & Advertiser Fraud Shield Nonce Signing KeyAADS_SECURITY_KEY=your_aads_fraud_shield_secret_key_here
# ==============================================================================# 12. ARTIFICIAL INTELLIGENCE & LLM APIS (HADITH & TAFSEER RAG)# ==============================================================================# DeepSeek API (Primary Q&A engine)DEEPSEEK_API_KEY=your_deepseek_api_key_here
# xAI Grok API (Secondary fallback engine)XAI_API_KEY=your_xai_api_key_here
# OpenRouter Unified API (Multi-model routing)OPENROUTER_API_KEY=your_openrouter_api_key_here
# Cohere API (Semantic Reranking)COHERE_API_KEY=your_cohere_api_key_here
# Dedicated Reranker API KeyRERANKER_API_KEY=your_reranker_api_key_here
# Local Model Execution Concurrency (Thread pool clamped between 1 and 16)ML_CONCURRENCY=2
# ==============================================================================# 13. TRANSACTIONAL EMAIL & NOTIFICATIONS# ==============================================================================# Resend Email Service (Primary HTTP API)RESEND_API_KEY=your_resend_api_key_hereEMAIL_FROM=Sahih Islam <sahihislamsupport@gmail.com>
# Standard SMTP Fallback (e.g. Gmail App Password, Amazon SES, SendGrid)SMTP_HOST=smtp.gmail.comSMTP_PORT=587SMTP_USER=sahihislamsupport@gmail.comSMTP_PASSWORD=your_smtp_app_password_hereSMTP_FROM=sahihislamsupport@gmail.com
# ==============================================================================# 14. E-COMMERCE & PLATFORM SETTINGS# ==============================================================================# Enable Marketplace checkout (0 = disabled/preview, 1 = enabled)ENABLE_MARKETPLACE_CHECKOUT=0
# Platform Owner Bank & UPI Configuration (For shopkeeper commission settlement)OWNER_ACCOUNT_NUMBER=OWNER_ACCOUNT_HOLDER=OWNER_BANK_NAME=OWNER_IFSC=OWNER_UPI_ID=PLATFORM_COMMISSION_PERCENT=7.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# ==============================================================================# SAHIH ISLAM ENTERPRISE - PRODUCTION ENVIRONMENT CONFIGURATION (.env.production)# ==============================================================================# Architecture Profile: Live Public Production Deployment# Databases: Live clusters `sahihislam`, `sahihislam_admin`, `sahihislam_commerce`# STRICT FAIL-CLOSED SECURITY:# - SECRET_KEY MUST be at least 32 characters and non-default.# - MONGO_URI is required and strictly audited.# - ALLOWED_ORIGINS cannot contain localhost, 127.0.0.1, or LAN addresses.# - Production environment cannot bind to test/dev databases.# ==============================================================================
# Application Environment Tier (Enforces strict fail-closed startup validation)APP_ENV=productionPORT=7860
# Database Configuration (Production MongoDB Atlas M0 / Dedicated)MONGO_URI=mongodb+srv://prod_app_user:STRONG_SECURE_PASSWORD@prod-cluster.mongodb.net/sahihislam?retryWrites=true&w=majorityMONGO_DB_NAME=sahihislamMONGO_DB_ADMIN_NAME=sahihislam_adminMONGO_DB_COMMERCE_NAME=sahihislam_commerceMONGO_MAX_POOL_SIZE=50MONGO_MIN_POOL_SIZE=5MONGO_WAIT_QUEUE_TIMEOUT_MS=5000
# Cache & Distributed Rate Limiting (Production Upstash / Redis Cloud over TLS)REDIS_URL=rediss://default:PROD_REDIS_PASSWORD@prod-redis.upstash.io:6379ENABLE_RATE_LIMIT=1ENABLE_REDIS_RATE_LIMIT=1
# Security & Staff Master Key (Cryptographically Secure >= 32 characters)# Generate with: python -c "import secrets; print(secrets.token_urlsafe(48))"SECRET_KEY=GENERATE_SECURE_TOKEN_AT_LEAST_32_CHARS_LONGSTAFF_SECRET_KEY=GENERATE_SECURE_TOKEN_AT_LEAST_32_CHARS_LONG
# CORS Allowed Origins (STRICT: Production HTTPS domains only; NO localhost allowed)ALLOWED_ORIGINS=https://sahihislam.com,https://admin.sahihislam.com,https://api-proxy.sahihislamapp.workers.dev
# Proxy & Network IsolationTRUSTED_PROXY_COUNT=1# Bind strictly to Cloudflare Edge IP CIDRs or local reverse-proxy socketsTRUSTED_PROXY_HOSTS=127.0.0.1,::1
# Firebase Authentication & Admin SDKFIREBASE_PROJECT_ID=sahih-islam-app# Supply either a path to the mounted Kubernetes/Cloud secret or the raw JSON / base64 stringFIREBASE_ADMIN_CREDENTIALS=/etc/secrets/firebase_credentials.json# Alternative: FIREBASE_CREDENTIALS_JSON='{"type": "service_account", ...}'
# Google Play In-App Billing (Google Play Developer API Service Account)GOOGLE_PLAY_PACKAGE_NAME=com.sahihislam.appGOOGLE_PLAY_SERVICE_ACCOUNT_KEY=/etc/secrets/google_play_service_account.json
# Cloudflare R2 Storage (Edge Audio, Tafseer, and Asset Distribution)CLOUDFLARE_ACCOUNT_ID=d7fc285dc6825480f6d8c887f93e7084R2_ACCESS_KEY_ID=PROD_R2_ACCESS_KEY_IDR2_SECRET_ACCESS_KEY=PROD_R2_SECRET_ACCESS_KEYR2_BUCKET_NAME=sahihislamR2_PUBLIC_DOMAIN=https://cdn.sahihislam.comCF_WORKER_URL=https://api-proxy.sahihislamapp.workers.dev
# LLM Providers (Multi-lingual Hybrid RAG & Hadith AI)DEEPSEEK_API_KEY=PROD_DEEPSEEK_API_KEYXAI_API_KEY=PROD_XAI_API_KEYOPENROUTER_API_KEY=PROD_OPENROUTER_API_KEYML_CONCURRENCY=4
# ObservabilityLOG_LEVEL=INFO12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# ==============================================================================# SAHIH ISLAM ENTERPRISE - STAGING ENVIRONMENT CONFIGURATION (.env.staging)# ==============================================================================# Architecture Profile: Pre-Release Acceptance & Load Testing# Databases: Isolated to `sahihislam_staging`, `sahihislam_staging_admin`, `sahihislam_staging_commerce`# Mirrors production security and TLS without touching live user data.# ==============================================================================
# Application Environment TierAPP_ENV=stagingPORT=7860
# Database Configuration (MongoDB Atlas Staging Cluster)MONGO_URI=mongodb+srv://staging_user:STAGING_STRONG_PASSWORD_HERE@staging-cluster.mongodb.net/sahihislam_staging?retryWrites=true&w=majorityMONGO_DB_NAME=sahihislam_stagingMONGO_DB_ADMIN_NAME=sahihislam_staging_adminMONGO_DB_COMMERCE_NAME=sahihislam_staging_commerceMONGO_MAX_POOL_SIZE=30MONGO_MIN_POOL_SIZE=5MONGO_WAIT_QUEUE_TIMEOUT_MS=5000
# Cache & Distributed Rate Limiting (Upstash / Redis Cloud over TLS)REDIS_URL=rediss://default:STAGING_REDIS_PASSWORD@staging-redis.upstash.io:6379ENABLE_RATE_LIMIT=1ENABLE_REDIS_RATE_LIMIT=1
# Security & Staff Master Key (High-Entropy Secret >= 32 characters)SECRET_KEY=REPLACE_WITH_STAGING_HIGH_ENTROPY_KEY_32_CHARS_MINSTAFF_SECRET_KEY=REPLACE_WITH_STAGING_HIGH_ENTROPY_KEY_32_CHARS_MIN
# CORS Allowed Origins# Staging web portals and internal QA harnesses onlyALLOWED_ORIGINS=https://staging.sahihislam.com,https://staging-admin.sahihislam.com
# Proxy & Network IsolationTRUSTED_PROXY_COUNT=1# Comma-separated list of Cloudflare or reverse-proxy egress IPsTRUSTED_PROXY_HOSTS=127.0.0.1,::1
# Firebase Authentication & Admin SDKFIREBASE_PROJECT_ID=sahih-islam-staging# Base64-encoded service account JSON or path to serviceAccountKey.jsonFIREBASE_ADMIN_CREDENTIALS=/etc/secrets/firebase_staging_service_account.json
# Google Play In-App Billing (Internal Test Track Sandbox)GOOGLE_PLAY_PACKAGE_NAME=com.sahihislam.appGOOGLE_PLAY_SERVICE_ACCOUNT_KEY=/etc/secrets/google_play_staging_service_account.json
# Cloudflare R2 Storage (Edge Audio & Assets - Staging Bucket)CLOUDFLARE_ACCOUNT_ID=d7fc285dc6825480f6d8c887f93e7084R2_ACCESS_KEY_ID=staging_r2_access_keyR2_SECRET_ACCESS_KEY=staging_r2_secret_keyR2_BUCKET_NAME=sahihislam-stagingR2_PUBLIC_DOMAIN=https://staging-cdn.sahihislam.comCF_WORKER_URL=https://staging-api-proxy.sahihislamapp.workers.dev
# LLM Providers (Hadith & Quran Multi-lingual AI)DEEPSEEK_API_KEY=staging_deepseek_keyXAI_API_KEY=staging_xai_keyOPENROUTER_API_KEY=staging_openrouter_keyML_CONCURRENCY=2
# ObservabilityLOG_LEVEL=INFO1*.apk filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# =========================================================# BACKEND GITIGNORE# =========================================================# Secrets and per-developer config.env.env.*!.env.example!.env.*.example*.jks*.keystore*.p12*.pem*.keykey.propertieslocal.properties*credentials*.json*service_account*.json.firebase/.wrangler/
# Python__pycache__/*.pyc*.py[cod]*$py.class*.egg-info/.venv/venv/.pytest_cache/.mypy_cache/
# Logs*.logbackend.logbackend_stdout.logbackend_stderr.log
# IDE.idea/.vscode/*.swp
# OS.DS_StoreThumbs.db
# Firebase service account JSON (machine-specific)firebase_credentials*.json!firebase_credentials.example.json
# ONNX models — downloaded at runtime via snapshot_download(), never committedbge_m3_onnx/cross_encoder_onnx/
# Local-only data backupsquran.backup.json*.backup.json
# Local audio cache and SQLite databasesdata/audio/data/qaida_audio/data/quran_pdfs/data/quran_tafseer/data/quran_translation/data/quran_translations/data/translation_audio/data/translation_audio_samples/data/quran_translation_audio/data/cache/data/cookies.txt.wrangler/*.dbdata/*.dbdata/tafseers.dbscripts/*.json
# Large media, binaries, and archive files (Stored on external CDNs / R2)*.mp3*.wav*.ogg*.m4a*.apk*.aab*.dex*.onnx*.onnx_data*.safetensors*.bin*.so*.dylib*.dll*.exe*.zip*.tar.gz*.rar
locustfile*.pyreports/exports/static/uploads/multilingual_*.jsonembedding_coverage_manifest.json!data/*.json
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295# R2 Integration Summary
## ✅ What's Been Done
### 1. Backend Configuration- ✅ Created `app/r2_config.py` - Secure R2 client with boto3- ✅ Created `app/r2_routes.py` - FastAPI routes for signed URLs- ✅ Integrated R2 routes in `run.py`- ✅ Added `boto3` to `requirements.txt`- ✅ Updated `.env.example` with R2 credentials template- ✅ CORS configured on R2 bucket (not needed for signed URLs, but done)
### 2. Security Implementation- ✅ R2 bucket kept **private** (no public access)- ✅ Backend generates **signed URLs** (expire in 1 hour)- ✅ Credentials stored in `.env` (not in Flutter)- ✅ Uses S3-compatible API via boto3
### 3. Documentation- ✅ `CLOUDFLARE_R2_SETUP.md` - Complete R2 setup guide- ✅ `R2_CREDENTIALS_SETUP.md` - How to create R2 access keys- ✅ `.env.example` - Template for environment variables
## 📋 What You Need to Do Next
### Step 1: Create R2 Access Keys1. Go to Cloudflare Dashboard2. Navigate to R2 > Manage R2 API Tokens3. Create API Token with: - **Permissions:** Object Read (minimum) - **Bucket:** sahihislam only4. **Copy credentials immediately:** - Access Key ID - Secret Access Key
**See:** `R2_CREDENTIALS_SETUP.md` for detailed steps
### Step 2: Add Credentials to .envEdit `BACKEND/.env` and add:
```envCLOUDFLARE_ACCOUNT_ID=d7fc285dc6825480f6d8c887f93e7084R2_ACCESS_KEY_ID=<your_access_key_id>R2_SECRET_ACCESS_KEY=<your_secret_access_key>```
###Step 3: Upload Tafseer Files to R2The 115 Tafseer files (~450 MB) need to be uploaded properly:
```powershell# Navigate to project directorycd D:\Project-x
# Upload all Tafseer filesGet-ChildItem "quran_tafseer\*.json" | ForEach-Object { $filename = $_.Name Write-Host "Uploading $filename..." -ForegroundColor Cyan npx wrangler r2 object put "sahihislam/quran_tafseer/$filename" ` --file="quran_tafseer\$filename" ` --content-type="application/json" ` --remote}```
### Step 4: Test Locally```bashcd BACKENDpython run.py```
Then test endpoints:```GET http://localhost:7860/api/r2/healthGET http://localhost:7860/api/r2/tafseer/1 # Al-FatihahGET http://localhost:7860/api/r2/tafseer/list```
### Step 5: Push to Hugging Face
#### 5a. Add R2 Secrets to Hugging Face Space1. Go to your HF Space settings2. **Variables and secrets** tab3. Add these secrets: ``` R2_ACCESS_KEY_ID = <your_access_key> R2_SECRET_ACCESS_KEY = <your_secret_access> CLOUDFLARE_ACCOUNT_ID = d7fc285dc6825480f6d8c887f93e7084 ```
#### 5b. Update Hugging Face Repository```bashcd BACKEND
# Check git statusgit status
# Add new filesgit add app/r2_config.py app/r2_routes.py requirements.txt
# Commitgit commit -m "Add R2 integration with signed URLs for secure asset delivery"
# Push to Hugging Facegit push```
## 🔌 API Endpoints
### Quran Tafseer (Text Only)
#### List All Available Tafseer```GET /api/r2/tafseer/list```Returns list of all 114 Surahs with signed URLs
#### Get Specific Tafseer JSON```GET /api/r2/tafseer/{surah_number}```Example: `GET /api/r2/tafseer/1` returns Al-Fatihah Tafseer
Response includes JSON content directly (proxied from R2)
#### Get Direct Signed URL```GET /api/r2/tafseer/url/{surah_number}```Returns a temporary signed URL (valid for 1 hour) that Flutter can use directly
### Qaida Audio
```GET /api/r2/qaida/audio/{filename}GET /api/r2/qaida/audio/list```
### Nimaz Mutarjam Audio
```GET /api/r2/nimaz/audio/{filename}GET /api/r2/nimaz/audio/list```
### Health Check
```GET /api/r2/health```Tests R2 connectivity and returns status
## 🎯 Flutter Integration Example
### Fetch Tafseer with Signed URL```dartimport 'package:http/http.dart' as http;import 'dart:convert';
Future<Map<String, dynamic>> fetchTafseer(int surahNumber) async { final baseUrl = 'https://your-hf-space.hf.space'; // Method 1: Direct JSON response final response = await http.get( Uri.parse('$baseUrl/api/r2/tafseer/$surahNumber') ); if (response.statusCode == 200) { return json.decode(response.body); } throw Exception('Failed to load Tafseer');}
// Method 2: Get signed URL for cachingFuture<String> getTafseerUrl(int surahNumber) async { final baseUrl = 'https://your-hf-space.hf.space'; final response = await http.get( Uri.parse('$baseUrl/api/r2/tafseer/url/$surahNumber') ); if (response.statusCode == 200) { final data = json.decode(response.body); return data['url']; // Signed URL valid for 1 hour } throw Exception('Failed to get Tafseer URL');}```
### Stream Audio from R2```dartimport 'package:just_audio/just_audio.dart';
Future<void> playQaidaLesson(String filename) async { final baseUrl = 'https://your-hf-space.hf.space'; final player = AudioPlayer(); // Backend will return 307 redirect to signed URL final audioUrl = '$baseUrl/api/r2/qaida/audio/$filename'; await player.setUrl(audioUrl); await player.play();}```
## 📊 Benefits of This Implementation
### Security- ✅ R2 bucket is private (no direct public access)- ✅ All access via signed URLs (temporary, expire in 1 hour)- ✅ No credentials in Flutter app- ✅ Backend controls who can access what
### Performance- ✅ Signed URLs served directly from R2 CDN (fast global delivery)- ✅ Backend only generates URLs (minimal CPU/bandwidth)- ✅ Flutter can cache signed URLs for duration of validity
### Cost- ✅ No egress fees from R2- ✅ Backend traffic minimal (only URL generation, not file serving)- ✅ ~$0.50/month for 100k DAU
### Scalability- ✅ CDN handles all file delivery- ✅ Backend stays lightweight- ✅ Can serve millions of users
## 🚨 Important Notes
### Signed URL Expiration- Default: 1 hour (3600 seconds)- Configurable in `r2_config.py`: `SIGNED_URL_EXPIRATION`- Flutter should handle URL expiration and re-fetch if needed
### Bucket Must Stay Private- Do NOT enable public access on R2 bucket- Security depends on controlled access via signed URLs
### Credentials Security- Never commit `.env` to git (already in `.gitignore`)- Use Hugging Face Secrets for production- Don't share credentials via email/chat
### Upload StatusCurrently only 531 KB uploaded (likely just metadata). Need to run upload script to push all 115 Tafseer files (~450 MB).
## 🐛 Troubleshooting
### "Failed to generate signed URL"- Check R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY in .env
### "403 Forbidden"- Verify API token has Object Read permission for sahihislam bucket
### "Connection timeout"- Check CLOUDFLARE_ACCOUNT_ID is correct- Verify R2 endpoint URL
### Files showing as 531 KB instead of 450 MB- Previous uploads used `--local` mode or missing `--remote` flag- Re-run upload script with `--remote` flag
## 📚 Files Changed/Created
```BACKEND/├── app/│ ├── r2_config.py [NEW] - R2 client & URL generation│ ├── r2_routes.py [NEW] - FastAPI endpoints│ └── run.py [MODIFIED] - Added R2 router├── requirements.txt [MODIFIED] - Added boto3├── .env.example [MODIFIED] - Added R2 credentials template└── R2_INTEGRATION_SUMMARY.md [NEW] - This file
Root/├── CLOUDFLARE_R2_SETUP.md [NEW] - Complete setup guide├── R2_CREDENTIALS_SETUP.md [NEW] - How to create R2 keys├── r2-cors-config.json [NEW] - CORS config (applied)└── test_r2_integration.py [NEW] - Test script```
## ✅ Ready to Deploy!
Once you:1. Create R2 access keys2. Add them to `.env`3. Upload Tafseer files to R24. Test locally5. Add secrets to Hugging Face6. Push to Hugging Face
Your backend will securely serve assets from R2 with signed URLs! 🎉1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253---title: Sahih Islam SuperAdmin APIemoji: 🛡️colorFrom: indigocolorTo: purplesdk: gradiosdk_version: 5.20.0app_file: app.pypinned: falselicense: mitshort_description: SuperAdmin Backend API for Sahih Islam---
# Sahih Islam SuperAdmin API
Dedicated administrative and governance backend API server powering the Sahih Islam SuperAdmin Control Panel.
## Features
- 40+ REST API endpoints for superadmin operations (`/admin/*`)- User management & analytics- Financial audit, order dispute, & refund management- Masjid administration- Hadith database management- Advertisement system control & remote switches (`sendads` collection)- System settings & configuration- Audit logging & monitoring- Push notification system- Database query tools
## Authentication
All endpoints under `/admin/*` require Firebase authentication with superadmin privileges.Include the Firebase ID token in the `Authorization` header:```Authorization: Bearer <firebase_id_token>```
## API Documentation
- **Swagger UI**: `/docs`- **ReDoc**: `/redoc`- **Health Check**: `/health`- **Public Ad Switch Config**: `/ads/config`
## Environment Variables
Required secrets in Hugging Face Space settings:
- `MONGO_URI` - MongoDB Atlas connection string- `FIREBASE_CREDENTIALS_JSON` - Firebase Admin SDK credentials (as JSON string)- `ALLOWED_ORIGINS` - Comma-separated list of authorized frontend web origins for CORS- `TRUSTED_PROXY_HOSTS` - Comma-separated CIDR/IP list of trusted reverse proxies1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---title: Sahih Islam App Backend APIemoji: 🕌colorFrom: greencolorTo: bluesdk: gradiosdk_version: 5.20.0app_file: app.pypinned: falselicense: mitshort_description: Backend API engine for Sahih Islam mobile app---
# Sahih Islam App Backend API
Production backend API server powering the Sahih Islam mobile application (Quran, Hadith, Prayer times, Daily content, Multi-language AI translation, and Subscriptions).
## Core Capabilities
- **Sacred Texts & Translations**: Quran, Hadith collections, and authoritative multilingual translations (38 languages).- **Daily Content Pipeline**: Daily Ayah & Daily Hadith rotated nightly with 24-hr cached translations.- **Prayer Astronomy & Qibla**: Precision calculations with custom offsets and madhab adjustments.- **AI Spiritual Search & RAG**: Cloud-first semantic search across Quranic verses and authenticated Hadiths.- **Subscriptions & Purchases**: Google Play Billing RTDN, Apple StoreKit 2, and in-app commerce.- **AdMob Server Configuration**: Remote ad switches, cadence enforcement, and sacred page guards.- **User Progress & Qaza Tracker**: Lifetime qaza debt calculation, tasbeeh logs, and prayer consistency analytics.
## Authentication
All user endpoints require Firebase authentication:```Authorization: Bearer <firebase_id_token>```
## API Documentation
- **Swagger UI**: `/docs`- **ReDoc**: `/redoc`- **Health Check**: `/health`- **Public Ad Switch Config**: `/ads/config`- **Payment & Wallet Gateway**: `/payment/...` (unified Razorpay, Google Play, Apple StoreKit, and Ad Wallet)
## Environment Variables
Required secrets in Hugging Face Space settings:
- `MONGO_URI` - MongoDB Atlas connection string- `FIREBASE_CREDENTIALS_JSON` - Firebase Admin SDK credentials (as JSON string)- `ALLOWED_ORIGINS` - Comma-separated list of authorized frontend web origins for CORS (defaults to production domains)- `TRUSTED_PROXY_HOSTS` - Comma-separated CIDR/IP list of trusted reverse proxies1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253---title: Sahih Islam SuperAdmin APIemoji: 🛡️colorFrom: indigocolorTo: purplesdk: gradiosdk_version: 5.20.0app_file: app.pypinned: falselicense: mitshort_description: SuperAdmin Backend API for Sahih Islam---
# Sahih Islam SuperAdmin API
Dedicated administrative and governance backend API server powering the Sahih Islam SuperAdmin Control Panel.
## Features
- 40+ REST API endpoints for superadmin operations (`/admin/*`)- User management & analytics- Financial audit, order dispute, & refund management- Masjid administration- Hadith database management- Advertisement system control & remote switches (`sendads` collection)- System settings & configuration- Audit logging & monitoring- Push notification system- Database query tools
## Authentication
All endpoints under `/admin/*` require Firebase authentication with superadmin privileges.Include the Firebase ID token in the `Authorization` header:```Authorization: Bearer <firebase_id_token>```
## API Documentation
- **Swagger UI**: `/docs`- **ReDoc**: `/redoc`- **Health Check**: `/health`- **Public Ad Switch Config**: `/ads/config`
## Environment Variables
Required secrets in Hugging Face Space settings:
- `MONGO_URI` - MongoDB Atlas connection string- `FIREBASE_CREDENTIALS_JSON` - Firebase Admin SDK credentials (as JSON string)- `ALLOWED_ORIGINS` - Comma-separated list of authorized frontend web origins for CORS- `TRUSTED_PROXY_HOSTS` - Comma-separated CIDR/IP list of trusted reverse proxies11.0.0+24123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488"""Sahih Islam SuperAdmin API (Hugging Face Space - Gradio SDK)FastAPI Backend running natively on Hugging Face Spaces without Docker.Configured for ZeroGPU and CPU hardware compatibility."""import osos.environ["GRADIO_SSR_MODE"] = "False"
# Deployment environment resolution:# Production environments (Hugging Face Spaces, Docker production) must not silently default to test mode.if "APP_ENV" not in os.environ: if ( os.getenv("SPACE_ID") or os.getenv("HUGGINGFACE_SERVER") or os.getenv("HF_SPACE_ID") or os.getenv("SYSTEM") == "spaces" ): os.environ["APP_ENV"] = "production" else: os.environ["APP_ENV"] = "development"
import loggingimport asynciofrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom slowapi.errors import RateLimitExceededfrom slowapi import _rate_limit_exceeded_handlerfrom app.limiter import limiterfrom app.core.config import settings
# -------------------------------------------------------------# ZeroGPU Support for Hugging Face Spaces# -------------------------------------------------------------# When a Space is assigned ZeroGPU hardware (zero-a10g), Hugging Face# requires at least one module-level function decorated with @spaces.GPU# during startup. We provide a safe, high-availability wrapper here.# -------------------------------------------------------------try: import spaces HAS_SPACES = Trueexcept ImportError: HAS_SPACES = False
try: import torchexcept ImportError: torch = None
if HAS_SPACES: @spaces.GPU def zero_gpu_compute_node(query: str = "ping") -> str: """ ZeroGPU Compute Worker. Decorated with @spaces.GPU to satisfy Hugging Face ZeroGPU runtime supervisor. """ hardware_info = "ZeroGPU Cluster Attached" if torch is not None and torch.cuda.is_available(): try: hardware_info = f"NVIDIA GPU: {torch.cuda.get_device_name(0)}" except Exception: hardware_info = "NVIDIA CUDA Device Active" return f"Operational: {hardware_info} | Query: {query}"else: def zero_gpu_compute_node(query: str = "ping") -> str: return f"Operational: Standard CPU Host | Query: {query}"
# -------------------------------------------------------------# Hugging Face Hub Compatibility Shim# Fixes 'cannot import name HfFolder from huggingface_hub'# -------------------------------------------------------------try: import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class _HfFolderShim: @staticmethod def get_token(): return os.environ.get("HF_TOKEN") @staticmethod def save_token(token): pass @staticmethod def delete_token(): pass huggingface_hub.HfFolder = _HfFolderShimexcept Exception: pass
try: import gradio as grexcept ImportError: gr = None
# Configure logginglogging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)
# Import core routers fail-closed (PX-19: broken routers must fail startup instead of booting half-APIs)from app.superadmin_routes import router as superadmin_routerfrom app.auth import router as auth_routerfrom app.masjid_routes import router as masjid_routerfrom app.hadith import router as hadith_routerfrom app.ads_routes import router as ads_routerfrom app.payment_routes import router as payment_routerfrom app.tafsir_routes import router as tafsir_router, quran_pdf_routerfrom app.r2_routes import router as r2_routerfrom app.mufti_routes import router as mufti_routerfrom app.events_routes import router as events_routerfrom app.api.razorpay_standard import router as razorpay_standard_routerfrom app.shop_routes import router as shop_routerfrom app.api.contact import router as contact_routerfrom app.api.v1 import v1_router
from app.database import sendads_collection, system_settings_collectionfrom app.core.rate_limits import UploadSizeLimiterMiddlewarefrom app.core.runtime_settings import RuntimeControlMiddleware, build_public_app_version_payload
def _register_routes(fastapi_app): """Mounts CORS, SuperAdmin routes, auth routes, health check, and ad config onto the FastAPI app.""" from app.core.config import settings if getattr(fastapi_app.state, "superadmin_routes_mounted", False): return fastapi_app.state.superadmin_routes_mounted = True
# Centralized configuration validation (SI-SEC-005, NEW-009) try: settings.validate() except Exception as e: if settings.IS_PROD or settings.IS_STAGING: logger.critical(f"FATAL: Production/Staging configuration validation failed: {e}") raise RuntimeError(f"FATAL: Configuration validation failed: {e}") from e logger.warning(f"Configuration Validation Notice: {e}")
# Register rate limiter & global unhandled exception guard on fastapi_app fastapi_app.state.limiter = limiter fastapi_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@fastapi_app.exception_handler(Exception) async def global_unhandled_exception_handler(request, exc: Exception): logger.error( f"[UNHANDLED_EXCEPTION] {request.method} {request.url.path}: {exc}", exc_info=True, ) return JSONResponse( status_code=500, content={ "success": False, "error": "Internal Server Error", "message": "An unexpected error occurred. The engineering team has been alerted.", }, )
@fastapi_app.on_event("startup") async def _on_startup(): try: settings.validate() except Exception as e: if settings.IS_PROD or settings.IS_STAGING: logger.critical(f"FATAL: Startup configuration validation failed: {e}") raise RuntimeError(f"FATAL: Startup configuration validation failed: {e}") from e logger.warning(f"Startup configuration validation notice: {e}")
try: from app.infrastructure.mongodb import init_db_indexes await init_db_indexes() logger.info("✅ MongoDB Indexes Initialized via startup hook.") except Exception as e: if settings.IS_PROD or settings.IS_STAGING: logger.critical(f"FATAL: MongoDB index initialization failed: {e}", exc_info=True) raise RuntimeError(f"FATAL: MongoDB index initialization failed: {e}") from e logger.warning(f"Note on MongoDB index initialization: {e}")
try: from app.infrastructure.redis import redis_manager await redis_manager.init() logger.info("✅ Upstash Redis Manager Initialized via startup hook.") except Exception as e: logger.warning(f"Note on Redis initialization: {e}")
try: from app.rag.cache import reconcile_persisted_corpus_revision_marker, start_corpus_revision_reconciler reconciled_rev = await reconcile_persisted_corpus_revision_marker() if reconciled_rev: logger.info(f"✅ Reconciled persisted pending RAG corpus revision -> {reconciled_rev}") start_corpus_revision_reconciler() except Exception as e: logger.warning(f"Note on RAG corpus revision reconciler startup: {e}")
try: from app.payment_routes import reconcile_unapplied_wallet_transactions reconciled = await reconcile_unapplied_wallet_transactions() if reconciled: logger.info(f"✅ Reconciled {len(reconciled)} unapplied wallet transaction(s) on startup.") except Exception as e: logger.warning(f"Note on wallet reconciliation startup: {e}")
try: from app.superadmin_routes import start_account_deletion_worker, start_scheduled_notifications_worker asyncio.create_task(start_account_deletion_worker()) asyncio.create_task(start_scheduled_notifications_worker()) logger.info("✅ Automated Account Deletion & Scheduled Notifications Background Tasks Started.") except Exception as e: logger.warning(f"Note on Account Deletion / Notifications Worker startup: {e}")
try: from app.services.daily_content.coordinator import daily_coordinator asyncio.create_task(daily_coordinator.start_scheduler()) logger.info("Daily Content Coordinator (12:00 AM Asia/Kolkata) scheduler started.") except Exception as e: logger.warning(f"Note on Daily Content Coordinator startup: {e}")
try: from app.ads_routes import start_ad_config_realtime_watcher asyncio.create_task(start_ad_config_realtime_watcher()) logger.info("AdMob & Sponsored Ads realtime config watcher started.") except Exception as e: logger.warning(f"Note on AdMob realtime config watcher startup: {e}")
try: from app.shop_routes import checkout_recovery_loop stop_ev = asyncio.Event() fastapi_app.state.checkout_recovery_stop = stop_ev fastapi_app.state.checkout_recovery_task = asyncio.create_task( checkout_recovery_loop(interval_seconds=60, stop_event=stop_ev) ) logger.info("✅ Stranded Checkout Recovery Worker Started in app.py.") except Exception as e: logger.warning(f"Note on Checkout Recovery Worker startup: {e}")
try: import app.realtime as _realtime_mod _realtime_mod._pubsub_task = asyncio.create_task(_realtime_mod.start_realtime_pubsub_listener()) logger.info("✅ Realtime SSE Redis Pub/Sub Listener Started in app.py.") except Exception as e: logger.warning(f"Note on Realtime Pub/Sub listener startup: {e}")
@fastapi_app.on_event("shutdown") async def _on_shutdown(): try: from app.realtime import stop_realtime_pubsub_listener await stop_realtime_pubsub_listener() except Exception: pass stop_ev = getattr(fastapi_app.state, "checkout_recovery_stop", None) task = getattr(fastapi_app.state, "checkout_recovery_task", None) if stop_ev is not None: stop_ev.set() if task is not None and not task.done(): task.cancel()
logger.info("Mounting CORS, SuperAdmin routes, Auth routes, /health, and /ads/config onto FastAPI application...") # Dynamic regex CORS matching (NEW-020) if not settings.IS_PROD: cors_regex = r"^https?://(localhost|127\.0\.0\.1|10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3})(:[0-9]+)?$" elif bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces"): cors_regex = r"^https://[a-zA-Z0-9_-]+\.hf\.space$" else: cors_regex = None
fastapi_app.add_middleware( CORSMiddleware, allow_origins=settings.ALLOWED_ORIGINS, allow_origin_regex=cors_regex, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], allow_headers=["*"], expose_headers=["Content-Length", "Content-Type", "X-Request-ID"], max_age=600, ) fastapi_app.add_middleware(UploadSizeLimiterMiddleware, max_upload_bytes=None) fastapi_app.add_middleware(RuntimeControlMiddleware)
# 1. SuperAdmin Control Panel endpoints (/admin/...) fastapi_app.include_router(superadmin_router, prefix="/admin", tags=["SuperAdmin Control Panel"])
# 1b. Razorpay Standard Web Checkout if razorpay_standard_router is not None: fastapi_app.include_router(razorpay_standard_router, tags=["Razorpay Standard Web Checkout"])
# 1c. Contact Form & Believer Support (SI-SEC-017) fastapi_app.include_router(contact_router, tags=["Contact & Believer Support"])
# 1d. API v1 Unified Routes (/api/v1/...) fastapi_app.include_router(v1_router, prefix="/api", tags=["API v1"])
# 2. Authentication & Profile endpoints (/auth/...) fastapi_app.include_router(auth_router, prefix="/auth", tags=["Authentication & Profile"])
# 3. Masjid endpoints (/masjid/...) if masjid_router is not None: fastapi_app.include_router(masjid_router, prefix="/masjid", tags=["Masjids"])
# 4. Hadith & Daily content endpoints (/api/...) if hadith_router is not None: fastapi_app.include_router(hadith_router, prefix="/api", tags=["Hadith & AI Engine"])
# 5. Ad delivery endpoints (/ads/...) if ads_router is not None: fastapi_app.include_router(ads_router)
# 6. Payment & Subscription endpoints (/payment/...) # Note: payment_router already has prefix="/payment" defined on router. # Mounting without an additional prefix avoids duplicate /payment/payment routes. if payment_router is not None: fastapi_app.include_router(payment_router, tags=["Payment & Wallet Engine"])
# 7. Tafsir & Quran PDF Library endpoints (/api/...) if tafsir_router is not None: fastapi_app.include_router(tafsir_router, prefix="/api", tags=["Tafsir Engine"]) if quran_pdf_router is not None: fastapi_app.include_router(quran_pdf_router, prefix="/api", tags=["Quran PDF Library"]) if r2_router is not None: fastapi_app.include_router(r2_router, prefix="/api", tags=["Cloudflare R2 Assets"])
# 8. Events & Mufti if events_router is not None: fastapi_app.include_router(events_router, tags=["Events"]) if mufti_router is not None: fastapi_app.include_router(mufti_router, prefix="/mufti", tags=["Mufti Verification"]) if shop_router is not None: fastapi_app.include_router(shop_router, tags=["Marketplace & Shop"])
has_health = any(getattr(r, "path", None) == "/health" for r in getattr(fastapi_app, "routes", [])) if not has_health: @fastapi_app.get("/health") async def health_check(): return { "status": "ok", "service": "sahih-islam-backend", "worker_pid": os.getpid(), }
has_ready = any(getattr(r, "path", None) == "/health/ready" for r in getattr(fastapi_app, "routes", [])) if not has_ready: @fastapi_app.get("/health/ready") async def health_ready(): from app.database import db from app.infrastructure.redis import redis_manager try: await asyncio.wait_for(db.command("ping"), timeout=2.0) mongo_up = True except Exception: mongo_up = False redis_res = await redis_manager.ping() status_code = 200 if mongo_up else 503 return JSONResponse( status_code=status_code, content={ "status": "ready" if mongo_up else "not_ready", "components": {"mongodb": {"status": "up" if mongo_up else "down"}, "redis": redis_res}, }, )
if ads_router is None: @fastapi_app.get("/ads/config") async def get_public_ads_config(): try: config = await sendads_collection.find_one({"_id": "global_ad_config"}) if not config: return { "status": "ok", "ads_enabled": False, "real_ads_enabled": False, "min_seconds_between_ads": 300, "content_rating": "G", "banner_ads_enabled": False, "home_ads": True, "chat_ads": True, "hadith_ads": True, "tafsir_ads": True, "qaza_ads": True, } return { "status": "ok", "ads_enabled": config.get("ads_enabled", False), "real_ads_enabled": config.get("real_ads_enabled", False), "min_seconds_between_ads": config.get("min_seconds_between_ads", 300), "content_rating": config.get("content_rating", "G"), "banner_ads_enabled": config.get("banner_ads_enabled", False), "home_ads": config.get("home_ads", True), "chat_ads": config.get("chat_ads", True), "hadith_ads": config.get("hadith_ads", True), "tafsir_ads": config.get("tafsir_ads", True), "qaza_ads": config.get("qaza_ads", True), "instant_ad": config.get("instant_ad"), "updated_at": config.get("updated_at") } except Exception: return { "status": "ok", "ads_enabled": False, "real_ads_enabled": False, "min_seconds_between_ads": 300, "content_rating": "G", "banner_ads_enabled": False, "home_ads": True, "chat_ads": True, "hadith_ads": True, "tafsir_ads": True, "qaza_ads": True, }
@fastapi_app.get("/app/version") async def get_public_app_version(): """Public app release, SuperAdmin force-update, maintenance mode, feature flags, and software specs endpoint.""" from app.core.app_release import get_build_release_info
release_info = get_build_release_info() no_store = { "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0", "Pragma": "no-cache", "Expires": "0", } try: doc = await system_settings_collection.find_one({"_id": "main"}) payload = build_public_app_version_payload(doc, release_info=release_info) return JSONResponse(content=payload, headers=no_store) except Exception: payload = build_public_app_version_payload(None, release_info=release_info) return JSONResponse(content=payload, headers=no_store)
# Hook gr.routes.App.create_app so our routes are embedded inside demo.launch()try: if hasattr(gr, "routes") and hasattr(gr.routes, "App") and hasattr(gr.routes.App, "create_app"): _original_create_app = gr.routes.App.create_app
def _custom_create_app(*args, **kwargs): app = _original_create_app(*args, **kwargs) _register_routes(app) return app
gr.routes.App.create_app = _custom_create_app logger.info("Successfully hooked gr.routes.App.create_app for seamless FastAPI route injection.")except Exception as e: logger.warning(f"Could not hook gr.routes.App.create_app: {e}")
demo = Noneif gr is not None: # Build Gradio Status Dashboard for visual monitoring on Hugging Face with gr.Blocks(title="Sahih Islam SuperAdmin API", theme=gr.themes.Soft()) as demo: gr.Markdown("# 🕌 Sahih Islam SuperAdmin API Server") gr.Markdown("### ✅ Status: **ONLINE & OPERATIONAL** (Hugging Face Gradio SDK)") gr.Markdown(""" This Space hosts the SuperAdmin backend for **Sahih Islam**. #### 🚀 Quick Links: - **Interactive API Docs (Swagger)**: [/docs](/docs) - **ReDoc Documentation**: [/redoc](/redoc) - **Health Probe**: [/health](/health) - **Remote Ad Config Endpoint**: [/ads/config](/ads/config) - **SuperAdmin Routes**: `/admin/...` #### 🛡️ Authentication: All `/admin/*` operations require a valid Firebase ID Token with SuperAdmin privileges. """)
# Interactive diagnostics connected to @spaces.GPU with gr.Accordion("⚡ Compute & ZeroGPU Hardware Status", open=False): status_input = gr.Textbox(label="Test Input", value="Ping") status_btn = gr.Button("Inspect GPU Compute Node") status_output = gr.Textbox(label="Compute Node Response") status_btn.click(fn=zero_gpu_compute_node, inputs=status_input, outputs=status_output)
# Also attempt to register on demo.app if already instantiated if hasattr(demo, "app") and demo.app: _register_routes(demo.app)
# Launch the Gradio app and keep the main process alive permanentlyif __name__ == "__main__": if demo is not None: logger.info("Starting SuperAdmin API Server via demo.launch()...") demo.launch(server_name="0.0.0.0", server_port=7860) else: logger.info("Starting SuperAdmin API Server via uvicorn...") import uvicorn from fastapi import FastAPI standalone_app = FastAPI(title="Sahih Islam SuperAdmin API") _register_routes(standalone_app) uvicorn.run(standalone_app, host="0.0.0.0", port=7860) # Keep the server thread active permanently on Hugging Face Spaces (prevents exit) import time while True: time.sleep(3600)1# SuperAdmin Backend App Module1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906# =========================================================# ADS ROUTES - Real AADS System with Database & Wallet# =========================================================# Complete advertisement system with admin approval, analytics,# real-time tracking, and integrated wallet/payment system.# =========================================================
from fastapi import APIRouter, HTTPException, Depends, Query, Request, Responsefrom typing import Optional, List, Dict, Any, Tuplefrom datetime import datetime, timedeltafrom uuid import uuid4import asyncioimport loggingimport mathimport time
logger = logging.getLogger("sahihislam.ads")
from app.auth_deps import get_current_user, require_adminfrom app.database import ( ads_collection, products_collection, ad_analytics_collection, users_collection, wallets_collection, transactions_collection, sendads_collection, admob_telemetry_collection, orders_collection, financial_audit_logs_collection, db,)
ad_tracking_nonces_collection = db["ad_tracking_nonces"]from app.models import ( AdCreate, AdUpdate, AdResponse, AdStatus, AdEvent, AdAnalytics, WalletTopUpRequest, AdmobEventCreate,)from app.content_moderation import screen_submission_compliancefrom app.core.rate_limits import get_client_ip
router = APIRouter(prefix="/ads", tags=["ads"])
_NO_STORE_HEADERS = { "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0", "Pragma": "no-cache", "Expires": "0",}
def _apply_no_store_headers(response: Optional[Response]) -> None: """Ensure dynamic ad switches and active sponsored campaigns are never edge/browser cached.""" if response is None: return for header, value in _NO_STORE_HEADERS.items(): response.headers[header] = value
_DEFAULT_APP_ID = "ca-app-pub-2460169767220051~7008959496"_DEFAULT_PROD_INTERSTITIAL_ANDROID = "ca-app-pub-2460169767220051/5800564465"_DEFAULT_PROD_BANNER_ANDROID = "ca-app-pub-2460169767220051/6300978111"_DEFAULT_TEST_INTERSTITIAL_ANDROID = "ca-app-pub-3940256099942544/1033173712"_DEFAULT_TEST_BANNER_ANDROID = "ca-app-pub-3940256099942544/6300978111"_DEFAULT_TEST_INTERSTITIAL_IOS = "ca-app-pub-3940256099942544/4411468910"_DEFAULT_TEST_BANNER_IOS = "ca-app-pub-3940256099942544/2934735716"
_LAST_PUBLISHED_AD_CONFIG_UPDATED_AT: Optional[str] = None_LAST_PUBLISHED_SPONSORED_UPDATED_AT: Optional[str] = None_LAST_PUBLISHED_SETTINGS_UPDATED_AT: Optional[str] = None
def build_public_ad_config_payload( config: Optional[Dict[str, Any]], *, ads_feature_enabled: bool = True,) -> Dict[str, Any]: """Build normalized public AdMob config payload from a sendads document.""" cfg = config or {"ads_enabled": False} real_ads = bool(cfg.get("real_ads_enabled", False)) if ads_feature_enabled else False prod_interstitial = (cfg.get("admob_interstitial_id_android") or "").strip() or _DEFAULT_PROD_INTERSTITIAL_ANDROID prod_banner = (cfg.get("admob_banner_id_android") or "").strip() or _DEFAULT_PROD_BANNER_ANDROID
raw_instant = cfg.get("instant_ad") fresh_instant = None if ads_feature_enabled and isinstance(raw_instant, dict): try: ts_val = float(raw_instant.get("timestamp") or 0) if ts_val > 0 and abs(time.time() - ts_val) <= 90: fresh_instant = raw_instant except (TypeError, ValueError): fresh_instant = None
return { "status": "ok", "ads_enabled": bool(cfg.get("ads_enabled", False)) and ads_feature_enabled, "real_ads_enabled": real_ads, "min_seconds_between_ads": max(300, int(cfg.get("min_seconds_between_ads", 300))), "content_rating": cfg.get("content_rating", "G"), "banner_ads_enabled": bool(cfg.get("banner_ads_enabled", False)) and ads_feature_enabled, "home_ads": cfg.get("home_ads", True) if ads_feature_enabled else False, "chat_ads": cfg.get("chat_ads", True) if ads_feature_enabled else False, "hadith_ads": cfg.get("hadith_ads", True) if ads_feature_enabled else False, "tafsir_ads": cfg.get("tafsir_ads", True) if ads_feature_enabled else False, "qaza_ads": cfg.get("qaza_ads", True) if ads_feature_enabled else False, "admob_app_id_android": (cfg.get("admob_app_id_android") or "").strip() or _DEFAULT_APP_ID, "admob_interstitial_id_android": prod_interstitial, "admob_banner_id_android": prod_banner, "admob_rewarded_id_android": (cfg.get("admob_rewarded_id_android") or "").strip() or prod_interstitial, "admob_interstitial_id_ios": (cfg.get("admob_interstitial_id_ios") or "").strip(), "admob_banner_id_ios": (cfg.get("admob_banner_id_ios") or "").strip(), "test_interstitial_id_android": _DEFAULT_TEST_INTERSTITIAL_ANDROID, "test_interstitial_id_ios": _DEFAULT_TEST_INTERSTITIAL_IOS, "test_banner_id_android": _DEFAULT_TEST_BANNER_ANDROID, "test_banner_id_ios": _DEFAULT_TEST_BANNER_IOS, "interstitial_ad_unit_id": prod_interstitial if real_ads else _DEFAULT_TEST_INTERSTITIAL_ANDROID, "banner_ad_unit_id": prod_banner if real_ads else _DEFAULT_TEST_BANNER_ANDROID, "instant_ad": fresh_instant, "updated_at": cfg.get("updated_at"), }
# =========================================================# GLOBAL AD CONFIGURATION (CLIENT READ-ONLY)# =========================================================@router.get('/config')async def get_public_ad_config(response: Response = None): """ Public lightweight endpoint for mobile apps to fetch remote AdMob switches and Unit IDs on boot. - ads_enabled: Master kill switch for Google AdMob ads ONLY (never affects Sponsored Cards). - real_ads_enabled: Switch for AdMob Unit IDs (False = Google test ads, True = live production AdMob ads). """ _apply_no_store_headers(response) try: from app.core.runtime_settings import get_runtime_settings runtime_cfg = await get_runtime_settings() ads_feature_enabled = bool(runtime_cfg.get("features", {}).get("ads", True)) config = await sendads_collection.find_one({"_id": "global_ad_config"}) return build_public_ad_config_payload(config, ads_feature_enabled=ads_feature_enabled) except Exception: logger.error("AdMob configuration unavailable") raise HTTPException(status_code=503, detail="Ad configuration unavailable")
# =========================================================# ADMOB TELEMETRY & EVENT INGESTION (MOBILE SDK REPORTING)# =========================================================_TELEMETRY_RATE_LIMITS: Dict[str, List[float]] = {}_TELEMETRY_MAX_PER_MINUTE = 60
@router.post('/admob/event')@router.post('/admob/track')async def track_admob_event(event: AdmobEventCreate, request: Request): """ Ingests live AdMob lifecycle events from mobile devices: - request: SDK began preloading - loaded: ad loaded into memory - impression: ad presented full screen to user - click: user tapped the ad - failed_to_load: SDK failed to load ad (e.g. error 3 no fill, error 2 network) - failed_to_show: ad could not be displayed - dismissed: user closed the ad Hardened under F-06: - Allowlisted event types & bounded payloads - Sliding window IP rate-limiting (60/min) - Optional verified Firebase identity; only a hash is stored """ import time client_ip = request.client.host if (request and request.client) else "127.0.0.1" client_ip_hash = hashlib.sha256(client_ip.encode("utf-8")).hexdigest()[:16] now_ts = time.time() # 1. IP rate limiting (60 events/minute) via Redis with memory bounded eviction fallback (F-06) is_limited = False try: from app.infrastructure.redis import redis_manager current_count = await redis_manager.incr(f"admob_telemetry:{client_ip_hash}", expire_seconds=60) if current_count > _TELEMETRY_MAX_PER_MINUTE: is_limited = True except Exception: # Fallback to local memory sliding window pass
if not is_limited: if len(_TELEMETRY_RATE_LIMITS) > 500: stale_cutoff = now_ts - 300.0 stale_keys = [k for k, v in _TELEMETRY_RATE_LIMITS.items() if not v or v[-1] < stale_cutoff] for k in stale_keys: _TELEMETRY_RATE_LIMITS.pop(k, None)
timestamps = _TELEMETRY_RATE_LIMITS.get(client_ip, []) cutoff = now_ts - 60.0 timestamps = [t for t in timestamps if t > cutoff] if len(timestamps) >= _TELEMETRY_MAX_PER_MINUTE: _TELEMETRY_RATE_LIMITS[client_ip] = timestamps is_limited = True else: timestamps.append(now_ts) _TELEMETRY_RATE_LIMITS[client_ip] = timestamps
if is_limited: raise HTTPException(status_code=429, detail="AdMob telemetry rate limit exceeded")
# 2. Verify optional Firebase identity from the bearer token. Ignore any # client-supplied user_id and retain only a one-way pseudonymous hash. verified_uid = None auth_header = request.headers.get("Authorization", "") if auth_header.startswith("Bearer "): token = auth_header.split(" ", 1)[1].strip() try: from firebase_admin import auth as fb_auth decoded = fb_auth.verify_id_token(token) verified_uid = decoded.get("uid") except Exception: raise HTTPException(status_code=401, detail="Invalid telemetry authentication token")
try: now_dt = datetime.utcnow() safe_error_messages = { 0: "Ad SDK internal error", 1: "Invalid ad request", 2: "Ad network error", 3: "No ad inventory available", }
unit_id = (event.ad_unit_id or "").strip() official_test_units = { "ca-app-pub-3940256099942544/1033173712", "ca-app-pub-3940256099942544/4411468910", "ca-app-pub-3940256099942544/6300978111", "ca-app-pub-3940256099942544/2934735716", } classification = "test" if unit_id in official_test_units else "unverified" if unit_id and classification != "test": config = await sendads_collection.find_one({"_id": "global_ad_config"}) production_units = { (config or {}).get(key) for key in ( "admob_interstitial_id_android", "admob_banner_id_android", "admob_interstitial_id_ios", "admob_banner_id_ios", "admob_rewarded_id_android", ) } if unit_id in production_units: classification = "production" doc = { "event_type": event.event_type, "ad_unit_id": unit_id or None, "ad_format": (event.ad_format or "interstitial").strip().lower(), "platform": (event.platform or "android").strip().lower(), "ad_mode_classification": classification, "is_test_ad": classification == "test", "error_code": event.error_code, "error_message": safe_error_messages.get(event.error_code), "placement": event.placement, "duration_seconds": event.duration_seconds if event.duration_seconds is not None else 5, "user_id_hash": hashlib.sha256(verified_uid.encode("utf-8")).hexdigest() if verified_uid else None, "auth_status": "verified" if verified_uid else "anonymous", "client_ip_hash": client_ip_hash, "metadata": {}, "timestamp": now_dt.isoformat(), "created_at": now_dt, # Native BSON Date for TTL index "date": now_dt.strftime("%Y-%m-%d"), } res = await admob_telemetry_collection.insert_one(doc) return { "status": "ok", "event_id": str(res.inserted_id), "event_type": doc["event_type"], "timestamp": doc["timestamp"] } except Exception as e: logger.warning("Error logging AdMob event: %s", type(e).__name__) raise HTTPException(status_code=503, detail="AdMob telemetry unavailable") from e
import timeimport randomimport mathimport hmacimport hashlibimport os
# =========================================================# 🛡️ P0 ARCHITECTURAL SECURITY: AADS FRAUD SHIELD & LEDGER# =========================================================from app.core.config import settingsAADS_SECURITY_KEY = settings.admob.aads_security_key
# In-memory anti-replay nonce cache: nonce -> expiry_timestamp_BURNED_TRACKING_NONCES: Dict[str, float] = {}_NONCE_TTL_SECONDS = 900.0 # 15 minutes validity
# Frequency capping to prevent click/impression spamming from draining wallets_RECENT_BILLABLE_CLICKS: Dict[str, float] = {} # "ip:ad_id" -> last_click_ts_CLICK_BILLING_COOLDOWN = 180.0 # 3 minutes cooldown for billing same IP on same ad
_RECENT_BILLABLE_IMPRESSIONS: Dict[str, float] = {} # "ip:ad_id" -> last_imp_ts_IMPRESSION_BILLING_COOLDOWN = 45.0 # 45 seconds cooldown for billing same IP on same ad
def _cleanup_expired_security_entries(): """Periodic pruning of expired nonces and fraud filters to keep RAM bounded.""" now = time.time() expired_nonces = [n for n, exp in _BURNED_TRACKING_NONCES.items() if exp < now] for n in expired_nonces: _BURNED_TRACKING_NONCES.pop(n, None) expired_clicks = [k for k, ts in _RECENT_BILLABLE_CLICKS.items() if now - ts > _CLICK_BILLING_COOLDOWN * 2] for k in expired_clicks: _RECENT_BILLABLE_CLICKS.pop(k, None) expired_imps = [k for k, ts in _RECENT_BILLABLE_IMPRESSIONS.items() if now - ts > _IMPRESSION_BILLING_COOLDOWN * 2] for k in expired_imps: _RECENT_BILLABLE_IMPRESSIONS.pop(k, None)
def _get_aads_key() -> bytes: key = (settings.admob.aads_security_key or AADS_SECURITY_KEY or "").strip() return key.encode()
def generate_ad_tracking_token(ad_id: str, event_type: str = "impression") -> str: """Generate an HMAC-SHA256 signed tracking token scoped to event_type and valid for 15 minutes.""" ts = int(time.time()) nonce = uuid4().hex payload = f"{ad_id}:{event_type}:{ts}:{nonce}" sig = hmac.new(_get_aads_key(), payload.encode(), hashlib.sha256).hexdigest() return f"{payload}:{sig}"
async def verify_and_consume_ad_token( ad_id: str, token: Optional[str], expected_event_type: Optional[str] = None) -> Tuple[bool, str]: """ Validate token signature, expiration, event scoping, and single-use nonce. Enforces durable shared deduplication across Redis, MongoDB, and memory. Returns (is_valid, reason). """ if not token or not isinstance(token, str): return False, "missing_token" parts = token.strip().split(":") if len(parts) == 5: t_ad_id, t_event_type, t_ts_str, nonce, sig = parts if expected_event_type and t_event_type != expected_event_type: return False, f"event_type_mismatch: expected {expected_event_type}, got {t_event_type}" expected_payload = f"{t_ad_id}:{t_event_type}:{t_ts_str}:{nonce}" elif len(parts) == 4: from app.core.config import settings if settings.IS_PROD or getattr(settings, "IS_STAGING", False): return False, "legacy_tokens_prohibited" # Legacy 4-part token: ad_id:ts:nonce:sig t_ad_id, t_ts_str, nonce, sig = parts t_event_type = "legacy" expected_payload = f"{t_ad_id}:{t_ts_str}:{nonce}" else: return False, "malformed_token" if t_ad_id != ad_id: return False, "ad_id_mismatch" try: t_ts = int(t_ts_str) except ValueError: return False, "invalid_timestamp" now = time.time() if now - t_ts > _NONCE_TTL_SECONDS: return False, "token_expired" if t_ts > now + 60: return False, "token_from_future" full_expected_sig = hmac.new(_get_aads_key(), expected_payload.encode(), hashlib.sha256).hexdigest() expected_sig = full_expected_sig if len(sig) == 64 else full_expected_sig[:20] if not hmac.compare_digest(sig, expected_sig): return False, "invalid_signature" # Check 1: In-memory nonce cache if nonce in _BURNED_TRACKING_NONCES: return False, "token_already_consumed" distributed_recorded = False
# Check 2: Shared Redis SETNX (only counts as distributed if shared Redis is connected) try: from app.redis_client import redis_manager if redis_manager.is_shared_available: set_ok = await redis_manager.set_nx( f"ad_nonce:{nonce}", "1", expire_seconds=_NONCE_TTL_SECONDS, require_shared=True, raise_on_error=True, ) if not set_ok: _BURNED_TRACKING_NONCES[nonce] = now + _NONCE_TTL_SECONDS return False, "token_already_consumed" distributed_recorded = True except Exception as e: logger.debug(f"[AADS] Redis nonce check: {e}")
# Check 3: Durable MongoDB collection try: await ad_tracking_nonces_collection.insert_one({ "nonce": nonce, "ad_id": ad_id, "event_type": t_event_type, "created_at": datetime.utcnow() }) distributed_recorded = True except Exception as err: if "duplicate" in str(err).lower() or "e11000" in str(err).lower(): _BURNED_TRACKING_NONCES[nonce] = now + _NONCE_TTL_SECONDS return False, "token_already_consumed" logger.warning(f"[AADS] MongoDB nonce check error: {err}")
# Fail closed in production/staging if distributed anti-replay stores are both unavailable from app.core.config import settings if not distributed_recorded and (settings.IS_PROD or getattr(settings, "IS_STAGING", False)): logger.error("[AADS] Distributed anti-replay unavailable in production; failing closed") return False, "distributed_replay_unavailable"
# Burn in local memory _BURNED_TRACKING_NONCES[nonce] = now + _NONCE_TTL_SECONDS if len(_BURNED_TRACKING_NONCES) > 10000: _cleanup_expired_security_entries() return True, "valid"
# =========================================================# COST CONFIGURATION (Cost Per Impression/Click) - 10% DISCOUNT APPLIED# =========================================================# Standard industry competitive rates with 10% instant discount applied:COST_PER_IMPRESSION = 0.0009 # Was $0.001 per view -> $0.0009 (10% less)COST_PER_CLICK = 0.09 # Was $0.10 per click -> $0.09 (10% less)COST_PER_CONVERSION = 4.50 # Was $5.00 per conversion -> $4.50 (10% less)
# 🚀 IN-MEMORY CONCURRENCY CACHE (Scales to 100k+ active ads and millions of requests)_ACTIVE_ADS_CACHE: Dict[str, Any] = { "expires_at": 0.0, "data": []}_ACTIVE_ADS_CACHE_TTL = 60.0 # 60 seconds TTL
def invalidate_active_ads_cache(): _ACTIVE_ADS_CACHE["expires_at"] = 0.0 _ACTIVE_ADS_CACHE["data"] = []
def publish_ad_config_update(config_data: Dict[str, Any]) -> int: """Broadcast updated AdMob switches immediately to all connected SSE clients.""" global _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT updated_at = config_data.get("updated_at") if isinstance(updated_at, str) and updated_at: _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT = updated_at try: from app import realtime return realtime.publish_all("admob_config_updated", build_public_ad_config_payload(config_data)) except Exception as exc: logger.debug("AdMob realtime broadcast skipped: %s", exc) return 0
async def mark_sponsored_ads_updated(ad_id: str = "") -> int: """Invalidate sponsored ads cache locally and notify sibling instances/SSE clients.""" global _LAST_PUBLISHED_SPONSORED_UPDATED_AT invalidate_active_ads_cache() now_iso = datetime.utcnow().isoformat() _LAST_PUBLISHED_SPONSORED_UPDATED_AT = now_iso try: await sendads_collection.update_one( {"_id": "sponsored_ads_sync"}, {"$set": {"updated_at": now_iso, "ad_id": ad_id}}, upsert=True, ) except Exception as exc: logger.debug("Sponsored sync marker write skipped: %s", exc) try: from app import realtime return realtime.publish_all("sponsored_ads_updated", {"ad_id": ad_id, "updated_at": now_iso}) except Exception as exc: logger.debug("Sponsored realtime broadcast skipped: %s", exc) return 0
async def start_ad_config_realtime_watcher(poll_interval_seconds: float = 2.5) -> None: """Propagate DB config changes from sibling backend spaces to worker caches and SSE subscribers.""" global _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT, _LAST_PUBLISHED_SPONSORED_UPDATED_AT, _LAST_PUBLISHED_SETTINGS_UPDATED_AT from app import realtime from app.core.runtime_settings import invalidate_runtime_settings_cache, get_runtime_settings
while True: try: await asyncio.sleep(poll_interval_seconds) docs = await sendads_collection.find( {"_id": {"$in": ["global_ad_config", "sponsored_ads_sync", "system_settings_sync"]}} ).to_list(length=3) has_subs = realtime.total_subscribers() > 0 for doc in docs: doc_id = doc.get("_id") updated_at = doc.get("updated_at") if doc_id == "global_ad_config": if _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT is None: _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT = updated_at elif updated_at and updated_at != _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT: _LAST_PUBLISHED_AD_CONFIG_UPDATED_AT = updated_at if has_subs: realtime.publish_all("admob_config_updated", build_public_ad_config_payload(doc)) elif doc_id == "sponsored_ads_sync": if _LAST_PUBLISHED_SPONSORED_UPDATED_AT is None: _LAST_PUBLISHED_SPONSORED_UPDATED_AT = updated_at elif updated_at and updated_at != _LAST_PUBLISHED_SPONSORED_UPDATED_AT: _LAST_PUBLISHED_SPONSORED_UPDATED_AT = updated_at invalidate_active_ads_cache() if has_subs: realtime.publish_all( "sponsored_ads_updated", {"ad_id": doc.get("ad_id", ""), "updated_at": updated_at}, ) elif doc_id == "system_settings_sync": if _LAST_PUBLISHED_SETTINGS_UPDATED_AT is None: _LAST_PUBLISHED_SETTINGS_UPDATED_AT = updated_at elif updated_at and updated_at != _LAST_PUBLISHED_SETTINGS_UPDATED_AT: _LAST_PUBLISHED_SETTINGS_UPDATED_AT = updated_at invalidate_runtime_settings_cache() await get_runtime_settings(force_refresh=True) if has_subs: realtime.publish_all("system_settings_updated", {"updated_at": updated_at}) except asyncio.CancelledError: raise except Exception as exc: logger.debug("Ad config watcher iteration error: %s", exc)
def weighted_shuffle_ads(ads: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Weighted random sampling without replacement (Efraimidis-Spirakis). Probability of appearing first is strictly proportional to daily_budget. """ if len(ads) <= 1: return ads scored = [] for ad in ads: budget = float(ad.get("daily_budget") or ad.get("budget") or 50.0) weight = max(budget, 1.0) u = random.random() u = max(min(u, 0.9999999), 0.0000001) score = -math.log(u) / weight scored.append((score, ad)) scored.sort(key=lambda x: x[0]) return [x[1] for x in scored]
# =========================================================# HELPER FUNCTIONS# =========================================================
def calculate_ad_metrics(impressions: int, clicks: int, spent: float) -> dict: """Calculate CTR, CPC, and other metrics""" ctr = (clicks / impressions * 100) if impressions > 0 else 0.0 cpc = (spent / clicks) if clicks > 0 else 0.0 return { "ctr": round(ctr, 2), "cpc": round(cpc, 2) }
async def check_ad_ownership(ad_id: str, user_id: str) -> dict: """Verify user owns the ad campaign""" ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad campaign not found") if ad.get("advertiser_uid") != user_id: raise HTTPException(status_code=403, detail="You don't own this ad campaign") return ad
def serialize_doc(doc: Dict[str, Any]) -> Dict[str, Any]: if not doc: return {} clean = dict(doc) if "_id" in clean: clean["_id"] = str(clean["_id"]) return clean
# =========================================================# PUBLIC ENDPOINTS# =========================================================
def _attach_fresh_event_tokens(ads: List[dict]) -> List[dict]: """Dynamically attaches fresh single-use cryptographically signed tokens per client request (P2-ADS-01).""" result = [] for ad in ads: ad_copy = dict(ad) ad_id = ad_copy.get("ad_id") or ad_copy.get("id") or "" ad_copy["impression_token"] = generate_ad_tracking_token(ad_id, "impression") ad_copy["click_token"] = generate_ad_tracking_token(ad_id, "click") result.append(ad_copy) return result
def _filter_ads_by_scope(ads: List[dict], scope: Optional[str] = None, category: Optional[str] = None) -> List[dict]: """Filters active ads by category or tab execution scope (Books, Health, All).""" if not scope and not category: return ads
scope_lower = (scope or "").lower().strip() if scope_lower in ("", "all", "home") and not category: return ads
cat_lower = (category or "").lower().strip()
BOOK_CATEGORIES = { "islamic books & quran", "kids islamic toys & books", "books", "education", "islamic courses & services", } BOOK_KEYWORDS = ( "book", "quran", "ebook", "reference", "reading", "tafsir", "hadith", "publication", "library", "kitab", "mushaf", "bukhari", "read-pen" )
HEALTH_CATEGORIES = { "halal cosmetics & health", "herbal medicine & tibb-e-nabawi", "halal foods & honey", "dates & dry fruits", } HEALTH_KEYWORDS = ( "health", "cosmetic", "medicine", "tibb", "nabawi", "herbal", "honey", "skincare", "wellness", "remedy", "organic", "nutrition", "cure", "shifa", "cupping", "hijama", "black seed", "kalonji", "ajwa", "oil", "dates" )
result = [] for ad in ads: c = (ad.get("category") or "").strip().lower() title = (ad.get("title") or "").lower() desc = (ad.get("description") or "").lower()
if category and c != cat_lower: continue
if scope_lower in ("books", "book"): is_book = c in BOOK_CATEGORIES or any(k in c for k in BOOK_KEYWORDS) if not is_book and c in ("", "products", "other halal products", "general"): is_book = any(k in title or k in desc for k in BOOK_KEYWORDS) if not is_book: continue
elif scope_lower in ("health", "cosmetics"): is_health = c in HEALTH_CATEGORIES or any(k in c for k in HEALTH_KEYWORDS) if not is_health and c in ("", "products", "other halal products", "general"): is_health = any(k in title or k in desc for k in HEALTH_KEYWORDS) if not is_health: continue
result.append(ad) return result
@router.get("/active")async def get_active_ads( category: Optional[str] = Query(None, description="Optional category filter"), scope: Optional[str] = Query(None, description="Scope filter: 'books', 'health', or 'all'"), response: Response = None,): """ Get active, approved Sponsored Card advertisements tuned for 100,000+ ads scale. - Completely independent of Google AdMob master/mode switches (ads_enabled / real_ads_enabled). - Supports scope filtering: 'books' for Books tab, 'health' for Health & Cosmetics, 'all' (default) for Homepage. - Uses in-memory caching (invalidated on mutations) to absorb high read concurrency. - Compound index ranking by daily_budget descending for high-value bidder priority. - Batch advertiser resolution (O(1) lookup, zero N+1 queries). - Public endpoint - no authentication required. """ _apply_no_store_headers(response) now_ts = time.time() if now_ts < _ACTIVE_ADS_CACHE["expires_at"] and _ACTIVE_ADS_CACHE["data"] is not None: filtered = _filter_ads_by_scope(_ACTIVE_ADS_CACHE["data"], scope=scope, category=category) return _attach_fresh_event_tokens(weighted_shuffle_ads(filtered))
now = datetime.utcnow() max_start = now + timedelta(hours=14) min_end = now - timedelta(hours=24) # Query for active ads within date range using compound index projection = { "ad_id": 1, "title": 1, "description": 1, "image_url": 1, "destination_url": 1, "status": 1, "category": 1, "start_date": 1, "end_date": 1, "impressions": 1, "clicks": 1, "budget": 1, "daily_budget": 1, "spent": 1, "advertiser_uid": 1, "cta_text": 1, "targeting": 1, "_id": 1, }
cursor = ads_collection.find( { "status": "active", "$and": [ {"$or": [{"start_date": None}, {"start_date": {"$exists": False}}, {"start_date": {"$lte": max_start}}]}, {"$or": [{"end_date": None}, {"end_date": {"$exists": False}}, {"end_date": {"$gte": min_end}}]}, ] }, projection ).sort([("daily_budget", -1), ("budget", -1)]).limit(100) ads_list = await cursor.to_list(length=100) # 🚀 Batch fetch all advertiser details and wallet balance in single queries adv_uids = list({ad.get("advertiser_uid") for ad in ads_list if ad.get("advertiser_uid")}) adv_map = {} active_adv_wallets = set() if adv_uids: try: users_cursor = users_collection.find( {"uid": {"$in": adv_uids}}, {"uid": 1, "displayName": 1, "username": 1} ) users_list = await users_cursor.to_list(length=len(adv_uids)) adv_map = { u["uid"]: (u.get("displayName") or u.get("username") or "Advertiser") for u in users_list } except Exception: pass
try: wallets_cursor = wallets_collection.find( {"user_id": {"$in": adv_uids}}, {"user_id": 1, "balance": 1} ) wallets_list = await wallets_cursor.to_list(length=len(adv_uids)) for w in wallets_list: if float(w.get("balance", 0.0)) > 0: active_adv_wallets.add(w.get("user_id")) except Exception: pass
active_ads = [] for ad in ads_list: spent = float(ad.get("spent", 0.0)) budget = float(ad.get("budget", 0.0)) if budget > 0 and spent >= budget: continue
adv_uid = ad.get("advertiser_uid") # If advertiser has 0 or exhausted wallet balance, pause and skip from serving if adv_uid and adv_uid not in active_adv_wallets: try: await ads_collection.update_one( {"ad_id": ad.get("ad_id")}, {"$set": {"status": "paused", "updated_at": datetime.utcnow()}} ) except Exception: pass continue
advertiser_name = adv_map.get(adv_uid, "Advertiser") cta_text = ad.get("cta_text") or (ad.get("targeting") or {}).get("cta_text") or "Shop Now" active_ads.append({ "id": ad.get("ad_id", str(ad.get("_id", ""))), "_id": str(ad.get("_id", "")), "ad_id": ad.get("ad_id"), "title": ad.get("title", ""), "description": ad.get("description", ""), "image_url": ad.get("image_url", ""), "destination_url": ad.get("destination_url", ""), "status": ad.get("status", "active"), "category": ad.get("category", ""), "start_date": ad.get("start_date").isoformat() if isinstance(ad.get("start_date"), datetime) else str(ad.get("start_date", "")), "end_date": ad.get("end_date").isoformat() if isinstance(ad.get("end_date"), datetime) else str(ad.get("end_date", "")), "impressions": int(ad.get("impressions", 0)), "clicks": int(ad.get("clicks", 0)), "advertiser_name": advertiser_name, "budget": budget, "daily_budget": float(ad.get("daily_budget")) if ad.get("daily_budget") is not None else budget, "cta_text": cta_text, }) _ACTIVE_ADS_CACHE["expires_at"] = time.time() + _ACTIVE_ADS_CACHE_TTL _ACTIVE_ADS_CACHE["data"] = active_ads filtered = _filter_ads_by_scope(active_ads, scope=scope, category=category) return _attach_fresh_event_tokens(weighted_shuffle_ads(filtered))
async def _commit_ad_event_billing( *, ad: Dict[str, Any], ad_id: str, event_type: str, metric_field: str, cost: float, is_billable: bool, tx_prefix: str, tx_description: str, client_ip: str = "", conversion_id: Optional[str] = None, converted_user_uid: Optional[str] = None,) -> Dict[str, Any]: """ Shared atomic billing + budget ceiling commit for impression/click/conversion (PX-14). 1. Rejects before touching wallet if budget - spent < cost. 2. Claims ad budget & metric atomically on ads_collection first. 3. Debits advertiser wallet atomically (compensating ad spent if wallet lacks funds). 4. Writes immutable ledger record & daily analytics. """ budget = float(ad.get("budget", 0.0) or 0.0) spent = float(ad.get("spent", 0.0) or 0.0) adv_uid = ad.get("advertiser_uid") now_dt = datetime.utcnow()
if budget > 0 and cost > 0 and round(spent + cost, 6) > budget: await ads_collection.update_one( {"ad_id": ad_id}, {"$set": {"status": "completed", "updated_at": now_dt}}, ) invalidate_active_ads_cache() return {"success": False, "reason": "Budget exhausted"}
if budget > 0 and cost > 0: max_prior_spent = round(budget - cost, 6) budget_filter: Dict[str, Any] = { "ad_id": ad_id, "status": "active", "$or": [ {"budget": 0}, {"budget": {"$exists": False}}, { "$and": [ {"spent": {"$lte": max_prior_spent}}, {"$expr": {"$lte": [{"$add": [{"$ifNull": ["$spent", 0]}, cost]}, "$budget"]}}, ] }, ], } elif budget > 0: budget_filter = { "ad_id": ad_id, "status": "active", "$or": [{"budget": 0}, {"budget": {"$exists": False}}, {"spent": {"$lte": budget}}], } else: budget_filter = {"ad_id": ad_id, "status": "active"}
ad_upd = await ads_collection.update_one( budget_filter, { "$inc": {metric_field: 1, "spent": cost}, "$set": {"updated_at": now_dt}, }, ) ad_mc = getattr(ad_upd, "modified_count", None) if isinstance(ad_mc, (int, float)) and not isinstance(ad_mc, bool) and ad_mc == 0 and budget > 0: await ads_collection.update_one( {"ad_id": ad_id}, {"$set": {"status": "completed", "updated_at": now_dt}}, ) invalidate_active_ads_cache() return {"success": False, "reason": "Budget exhausted"}
if is_billable and adv_uid and cost > 0: debit_result = await wallets_collection.update_one( {"user_id": adv_uid, "balance": {"$gte": cost}}, { "$inc": {"balance": -cost}, "$set": {"updated_at": now_dt}, }, ) debit_mc = getattr(debit_result, "modified_count", None) if isinstance(debit_mc, (int, float)) and not isinstance(debit_mc, bool) and debit_mc == 0: # Roll back pre-claimed ad spent & pause campaign await ads_collection.update_one( {"ad_id": ad_id}, { "$inc": {metric_field: -1, "spent": -cost}, "$set": {"status": "paused", "updated_at": now_dt}, }, ) invalidate_active_ads_cache() return {"success": False, "reason": "Advertiser wallet balance exhausted"}
tx_doc: Dict[str, Any] = { "transaction_id": f"{tx_prefix}_{uuid4().hex[:12]}", "user_id": adv_uid, "type": "ad_spend", "ad_id": ad_id, "event_type": event_type, "description": tx_description, "amount": -cost, "currency": "INR", "status": "completed", "created_at": now_dt, } if client_ip: tx_doc["ip_address"] = client_ip if conversion_id: tx_doc["conversion_id"] = conversion_id if converted_user_uid: tx_doc["converted_user_uid"] = converted_user_uid
try: await transactions_collection.insert_one(tx_doc) except Exception as ledger_err: logger.critical(f"[AADS Ledger Failure] {event_type} ledger insert failed for {adv_uid}: {ledger_err}") try: await financial_audit_logs_collection.insert_one({ "audit_id": f"audit_ledger_fail_{uuid4().hex[:12]}", "action": "aads_ledger_failure", "entity_type": "ad_spend", "entity_id": ad_id, "target_user_id": adv_uid, "amount": -cost, "error": str(ledger_err), "timestamp": now_dt, }) except Exception as audit_err: logger.critical(f"[AADS Audit Failure] Could not write financial audit log: {audit_err}")
today = now_dt.date().isoformat() await ad_analytics_collection.update_one( {"ad_id": ad_id, "date": today}, { "$inc": {metric_field: 1, "spent": cost}, "$setOnInsert": {"created_at": now_dt}, }, upsert=True, ) return { "success": True, "ad_id": ad_id, "cost": cost, "billable": is_billable, "new_total_spent": round(spent + cost, 4), }
@router.post("/{ad_id}/impression")async def track_impression( ad_id: str, request: Request, event_data: Optional[dict] = None): """ Track an impression (ad view) for analytics. Features P0 Architectural Protections: - Cryptographic token & anti-replay validation. - Invalid impression filter (cooldown per IP/device). - Atomic wallet deduction with zero TOCTOU race conditions. - Immutable audit ledger logging in transactions_collection. """ ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad not found") if ad.get("status") != "active": return {"success": False, "reason": "Ad not active"} budget = float(ad.get("budget", 0.0)) spent = float(ad.get("spent", 0.0)) if budget > 0 and spent >= budget: await ads_collection.update_one( {"ad_id": ad_id}, {"$set": {"status": "completed", "updated_at": datetime.utcnow()}} ) invalidate_active_ads_cache() return {"success": False, "reason": "Budget exhausted"} # 1. Resolve client IP for fraud detection client_ip = get_client_ip(request)
# 2. Token validation (NEW-003: enforce valid cryptographic single-use token) token = (event_data or {}).get("token") if event_data else None token_valid, reason = await verify_and_consume_ad_token(ad_id, token, expected_event_type="impression") if not token_valid: logger.warning(f"[AADS Security] Rejected untrusted impression for ad {ad_id}: {reason} from IP {client_ip}") return {"success": False, "reason": f"Invalid or unverified token: {reason}"}
# 3. Frequency Capping / Invalid Impression Shield (45s window per IP) ip_key = f"{client_ip}:{ad_id}" now = time.time() # Distributed Redis Cooldown Check is_billable = True try: from app.redis_client import redis_manager redis_cd_key = f"aads:cooldown:imp:{ip_key}" acquired = await redis_manager.set_nx( redis_cd_key, "1", expire_seconds=_IMPRESSION_BILLING_COOLDOWN ) if not acquired: is_billable = False except Exception as e: logger.debug(f"[AADS] Redis impression cooldown fallback to memory: {e}") last_imp_ts = _RECENT_BILLABLE_IMPRESSIONS.get(ip_key, 0.0) is_billable = (now - last_imp_ts >= _IMPRESSION_BILLING_COOLDOWN) if is_billable: _RECENT_BILLABLE_IMPRESSIONS[ip_key] = now
cost = COST_PER_IMPRESSION if is_billable else 0.0 if is_billable: _RECENT_BILLABLE_IMPRESSIONS[ip_key] = now
return await _commit_ad_event_billing( ad=ad, ad_id=ad_id, event_type="impression", metric_field="impressions", cost=cost, is_billable=is_billable, tx_prefix="txn_imp", tx_description=f"AADS Impression: Ad {ad.get('title', ad_id)[:30]}", client_ip=client_ip, )
@router.post("/{ad_id}/click")async def track_click( ad_id: str, request: Request, event_data: Optional[dict] = None): """ Track a click (user clicked CTA button) for analytics. Features P0 Architectural Protections: - Cryptographic token & anti-replay verification. - Click fraud defense (3-minute cooldown per IP on billable clicks). - Strict atomic wallet deduction with $gte filter. - Immutable audit ledger logging in transactions_collection. """ ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad not found") if ad.get("status") != "active": return {"success": False, "reason": "Ad not active"} budget = float(ad.get("budget", 0.0)) spent = float(ad.get("spent", 0.0)) if budget > 0 and spent >= budget: await ads_collection.update_one( {"ad_id": ad_id}, {"$set": {"status": "completed", "updated_at": datetime.utcnow()}} ) invalidate_active_ads_cache() return {"success": False, "reason": "Budget exhausted"} # 1. Resolve client IP for fraud detection client_ip = get_client_ip(request)
# 2. Token validation (NEW-003: enforce valid cryptographic single-use token) token = (event_data or {}).get("token") if event_data else None token_valid, reason = await verify_and_consume_ad_token(ad_id, token, expected_event_type="click") if not token_valid: logger.warning(f"[AADS Security] Rejected untrusted click for ad {ad_id}: {reason} from IP {client_ip}") return {"success": False, "reason": f"Invalid or unverified token: {reason}"}
# 3. Frequency Capping / Click-Spam Shield (3-minute cooldown per IP) ip_key = f"{client_ip}:{ad_id}" now = time.time() # Distributed Redis Cooldown Check is_billable = True try: from app.redis_client import redis_manager redis_cd_key = f"aads:cooldown:click:{ip_key}" acquired = await redis_manager.set_nx( redis_cd_key, "1", expire_seconds=_CLICK_BILLING_COOLDOWN ) if not acquired: is_billable = False except Exception as e: logger.debug(f"[AADS] Redis click cooldown fallback to memory: {e}") last_click_ts = _RECENT_BILLABLE_CLICKS.get(ip_key, 0.0) is_billable = (now - last_click_ts >= _CLICK_BILLING_COOLDOWN) if is_billable: _RECENT_BILLABLE_CLICKS[ip_key] = now
cost = COST_PER_CLICK if is_billable else 0.0 if is_billable: _RECENT_BILLABLE_CLICKS[ip_key] = now
return await _commit_ad_event_billing( ad=ad, ad_id=ad_id, event_type="click", metric_field="clicks", cost=cost, is_billable=is_billable, tx_prefix="txn_clk", tx_description=f"AADS Verified Click: Ad {ad.get('title', ad_id)[:30]}", client_ip=client_ip, )
@router.post("/{ad_id}/conversion")async def track_conversion( ad_id: str, conversion_data: Optional[dict] = None, current_user: dict = Depends(get_current_user)): """ Track a conversion (purchase, signup, etc.) for analytics. Features P0 Architectural Protections (NEW-003): - Validates ad exists, is active, and budget is not exhausted. - Requires valid cryptographic tracking token. - Idempotency & deduplication by conversion ID. - Atomic wallet deduction with insufficient funds handling. """ ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad not found") if ad.get("status") != "active": return {"success": False, "reason": "Ad not active"} budget = float(ad.get("budget", 0.0)) spent = float(ad.get("spent", 0.0)) if budget > 0 and spent >= budget: await ads_collection.update_one( {"ad_id": ad_id}, {"$set": {"status": "completed", "updated_at": datetime.utcnow()}} ) invalidate_active_ads_cache() return {"success": False, "reason": "Budget exhausted"} # 1. Token validation token = (conversion_data or {}).get("token") if conversion_data else None token_valid, reason = await verify_and_consume_ad_token(ad_id, token, expected_event_type="conversion") if not token_valid: logger.warning(f"[AADS Security] Rejected untrusted conversion for ad {ad_id}: {reason}") return {"success": False, "reason": f"Invalid or unverified token: {reason}"} # 2. Conversion Attribution & Deduplication user_id = current_user.get("uid") adv_uid = ad.get("advertiser_uid") if adv_uid and adv_uid == user_id: return {"success": False, "reason": "Self-attribution disallowed"}
conv_id = (conversion_data or {}).get("conversion_id") or f"conv_{user_id}_{ad_id}" raw_conv_id = (conversion_data or {}).get("conversion_id") if raw_conv_id and (str(raw_conv_id).startswith("order_") or str(raw_conv_id).startswith("ord_")): verified_order = await orders_collection.find_one({ "$or": [{"order_id": raw_conv_id}, {"_id": raw_conv_id}], "buyer_uid": user_id, "status": {"$in": ["paid", "delivered", "confirmed", "completed"]} }) if not verified_order: return {"success": False, "reason": "No verified order matching conversion_id for user"} # Atomic single-conversion claim via ad_tracking_nonces_collection before debiting wallet conv_claim_nonce = f"conv:{ad_id}:{conv_id}" try: await ad_tracking_nonces_collection.insert_one({ "nonce": conv_claim_nonce, "ad_id": ad_id, "event_type": "conversion", "created_at": datetime.utcnow(), }) except Exception as conv_dup_err: if "duplicate" in str(conv_dup_err).lower() or "e11000" in str(conv_dup_err).lower(): return {"success": False, "reason": "Duplicate conversion event"} raise existing = await transactions_collection.find_one({ "ad_id": ad_id, "conversion_id": conv_id, "event_type": "conversion", }) if existing: return {"success": False, "reason": "Duplicate conversion event"} return await _commit_ad_event_billing( ad=ad, ad_id=ad_id, event_type="conversion", metric_field="conversions", cost=COST_PER_CONVERSION, is_billable=True, tx_prefix="txn_cnv", tx_description=f"AADS Conversion: Ad {ad.get('title', ad_id)[:30]}", conversion_id=conv_id, converted_user_uid=user_id, )
# =========================================================# ADVERTISER WALLET & BILLING ENDPOINTS# =========================================================
@router.get("/wallet")async def get_wallet(current_user: dict = Depends(get_current_user)): """ Get current user's advertiser wallet balance and recent transactions. Called by Advertiser Dashboard. """ user_id = current_user.get("uid") wallet = await wallets_collection.find_one({"user_id": user_id}) if not wallet: initial_wallet = { "user_id": user_id, "balance": 0.0, "currency": "INR", "created_at": datetime.utcnow(), "updated_at": datetime.utcnow() } await wallets_collection.insert_one(initial_wallet) wallet = initial_wallet balance = float(wallet.get("balance", 0.0)) # Get user transactions tx_cursor = transactions_collection.find({"user_id": user_id}).sort("created_at", -1).limit(50) tx_list = await tx_cursor.to_list(length=50) formatted_txs = [] for tx in tx_list: created_at_dt = tx.get("created_at") date_str = created_at_dt.isoformat() if isinstance(created_at_dt, datetime) else str(created_at_dt or "") formatted_txs.append({ "id": tx.get("transaction_id", str(tx.get("_id", ""))), "date": date_str, "description": tx.get("description", "Wallet Activity"), "amount": float(tx.get("amount", 0.0)), "status": tx.get("status", "completed"), "payment_method": tx.get("payment_method", "card") }) return { "balance": balance, "currency": wallet.get("currency", "INR"), "transactions": formatted_txs }
@router.post("/wallet/add-funds")async def add_wallet_funds( payload: Dict[str, Any], current_user: dict = Depends(get_current_user)): """ Administrative manual ad wallet credit adjustment. Restricted strictly to verified SuperAdmin or Finance staff adjusting ANOTHER account. Public, advertiser, self-crediting, and moderation ADMIN/APP_ADMIN deposits MUST go through verified payment gateway (/payment/web/razorpay/create-order with purpose 'ad_wallet'). """ from app.auth_deps import is_finance_or_superadmin from app.payment_routes import credit_wallet_durable_atomic
if not is_finance_or_superadmin(current_user): raise HTTPException( status_code=403, detail="Direct unverified wallet crediting is prohibited. Restricted to verified SuperAdmin or Finance staff; advertisers must use the verified payment gateway (/payment/web/razorpay/create-order)." )
caller_uid = current_user.get("uid") or "" target_uid = str(payload.get("target_user_id") or payload.get("user_id") or "").strip() if not target_uid: raise HTTPException( status_code=400, detail="target_user_id is required for administrative wallet adjustment." ) if target_uid == caller_uid: raise HTTPException( status_code=403, detail="Self-crediting via administrative wallet endpoint is forbidden." )
raw_amount = payload.get("amount") if raw_amount is None: raise HTTPException(status_code=400, detail="Amount is required")
try: amount = float(raw_amount) except (ValueError, TypeError): raise HTTPException(status_code=400, detail="Invalid amount")
if not math.isfinite(amount) or amount <= 0: raise HTTPException(status_code=400, detail="Amount must be a finite value greater than zero") if amount > 100000.0: raise HTTPException(status_code=400, detail="Administrative wallet adjustment cannot exceed ₹100,000 per request.")
tx_id = str(payload.get("transaction_id") or payload.get("idempotency_key") or f"tx_{uuid4().hex[:12]}").strip() reason = str(payload.get("reason") or "Manual Administrative Ledger Adjustment").strip() audit_data = { "authorized_by_admin_uid": caller_uid, "authorized_by_admin_email": current_user.get("email"), "target_user_id": target_uid, }
credit_res = await credit_wallet_durable_atomic( user_id=target_uid, amount=amount, transaction_id=tx_id, description=f"Admin Adjustment: {reason}", payment_method="manual_admin_adjustment", payment_domain="admin", audit_data=audit_data, notes=reason, )
return { "success": True, "message": f"Successfully added ₹{amount:.2f} to target wallet", "target_user_id": target_uid, "amount": amount, "balance": credit_res["balance"], "transaction_id": tx_id, "already_processed": credit_res.get("already_processed", False), }
# =========================================================# ADVERTISER CAMPAIGN MANAGEMENT# =========================================================
@router.get("/my-campaigns")async def get_my_campaigns( current_user: dict = Depends(get_current_user), status: Optional[str] = None): """ Get all campaigns/ads created by the current user. """ user_id = current_user.get("uid") query: Dict[str, Any] = {"advertiser_uid": user_id} if status and status != "All": query["status"] = status.lower() cursor = ads_collection.find(query).sort("created_at", -1) campaigns = await cursor.to_list(length=200) result = [] for ad in campaigns: impressions = int(ad.get("impressions", 0)) clicks = int(ad.get("clicks", 0)) spent = float(ad.get("spent", 0.0)) metrics = calculate_ad_metrics(impressions, clicks, spent) result.append({ "id": ad.get("ad_id", str(ad.get("_id", ""))), "_id": str(ad.get("_id", "")), "ad_id": ad.get("ad_id"), "title": ad.get("title", ""), "description": ad.get("description", ""), "image_url": ad.get("image_url", ""), "destination_url": ad.get("destination_url", ""), "status": ad.get("status", "draft"), "category": ad.get("category", ""), "budget": float(ad.get("budget", 0)), "daily_budget": float(ad["daily_budget"]) if ad.get("daily_budget") else None, "spent": spent, "impressions": impressions, "clicks": clicks, "conversions": int(ad.get("conversions", 0)), "ctr": metrics["ctr"], "cpc": metrics["cpc"], "start_date": ad.get("start_date").isoformat() if isinstance(ad.get("start_date"), datetime) else str(ad.get("start_date", "")), "end_date": ad.get("end_date").isoformat() if isinstance(ad.get("end_date"), datetime) else str(ad.get("end_date", "")), "created_at": ad.get("created_at").isoformat() if isinstance(ad.get("created_at"), datetime) else str(ad.get("created_at", "")), "rejection_reason": ad.get("rejection_reason"), "cta_text": ad.get("cta_text") or (ad.get("targeting") or {}).get("cta_text") or "Shop Now", "targeting": ad.get("targeting") or {}, }) return result
@router.post("/create")async def create_campaign( campaign_data: AdCreate, current_user: dict = Depends(get_current_user)): """ Create a new ad campaign. Automatically screened for Islamic compliance. Requires available advertiser wallet balance (> 0). """ user_id = current_user.get("uid") user_email = current_user.get("email", "")
# 💰 1. Verify advertiser has available wallet balance before allowing ad creation wallet = await wallets_collection.find_one({"user_id": user_id}) wallet_balance = float(wallet.get("balance", 0.0)) if wallet else 0.0 if wallet_balance <= 0: raise HTTPException( status_code=400, detail="Cannot post ad without wallet balance. Please add funds to your wallet to launch a campaign." )
if float(campaign_data.budget) > wallet_balance: raise HTTPException( status_code=400, detail=f"Not enough balance. Your campaign budget (₹{campaign_data.budget:.2f}) cannot exceed your available wallet balance (₹{wallet_balance:.2f})." ) category_val = campaign_data.category.value if hasattr(campaign_data.category, "value") else str(campaign_data.category) cta_text_val = (campaign_data.cta_text or (campaign_data.targeting or {}).get("cta_text") or "Shop Now").strip()
# 🛡️ Automated Islamic Marketplace Compliance Screening via DeepSeek-Flash await screen_submission_compliance( title=campaign_data.title, description=campaign_data.description, category=category_val, image_url=campaign_data.image_url, destination_url=campaign_data.destination_url, item_type="ad" ) ad_id = f"ad_{uuid4().hex[:12]}" now = datetime.utcnow() start_dt = campaign_data.start_date if start_dt and isinstance(start_dt, datetime): # Normalize to naive UTC for safe comparison and MongoDB storage start_dt = start_dt.replace(tzinfo=None) if start_dt.tzinfo else start_dt if start_dt <= now + timedelta(hours=24): start_dt = min(start_dt, now)
end_dt = campaign_data.end_date if end_dt and isinstance(end_dt, datetime): end_dt = end_dt.replace(tzinfo=None) if end_dt.tzinfo else end_dt
ad_doc = { "ad_id": ad_id, "advertiser_uid": user_id, "advertiser_email": user_email, "title": campaign_data.title, "description": campaign_data.description, "image_url": campaign_data.image_url, "destination_url": campaign_data.destination_url, "category": category_val, "status": AdStatus.ACTIVE.value, "budget": float(campaign_data.budget), "daily_budget": float(campaign_data.daily_budget) if campaign_data.daily_budget else None, "cta_text": cta_text_val, "spent": 0.0, "impressions": 0, "clicks": 0, "conversions": 0, "start_date": start_dt, "end_date": end_dt, "targeting": campaign_data.targeting or {}, "created_at": now, "updated_at": now } result = await ads_collection.insert_one(ad_doc) ad_doc["_id"] = str(result.inserted_id) invalidate_active_ads_cache() return { "success": True, "message": "Campaign approved and published successfully", "ad_id": ad_id, "campaign": serialize_doc(ad_doc) }
@router.post("/{ad_id}/update")async def update_campaign( ad_id: str, campaign_data: AdUpdate, current_user: dict = Depends(get_current_user)): """ Update an existing ad campaign. """ user_id = current_user.get("uid") ad = await check_ad_ownership(ad_id, user_id)
if campaign_data.budget is not None and float(campaign_data.budget) > 0: wallet = await wallets_collection.find_one({"user_id": user_id}) wallet_balance = float(wallet.get("balance", 0.0)) if wallet else 0.0 if float(campaign_data.budget) > wallet_balance: raise HTTPException( status_code=400, detail=f"Not enough balance. Your campaign budget (₹{campaign_data.budget:.2f}) cannot exceed your available wallet balance (₹{wallet_balance:.2f})." ) update_doc: Dict[str, Any] = {"updated_at": datetime.utcnow()} for field, value in campaign_data.model_dump(exclude_unset=True).items(): if value is not None: if field == "category" and hasattr(value, "value"): update_doc[field] = value.value else: update_doc[field] = value
if "cta_text" not in update_doc and "targeting" in update_doc and isinstance(update_doc["targeting"], dict): if update_doc["targeting"].get("cta_text"): update_doc["cta_text"] = update_doc["targeting"]["cta_text"]
# 🛡️ Screen updated fields for compliance if modified if any(k in update_doc for k in ["title", "description", "category", "image_url", "destination_url"]): cat_str = update_doc.get("category", ad.get("category", "General")) await screen_submission_compliance( title=update_doc.get("title", ad.get("title", "")), description=update_doc.get("description", ad.get("description", "")), category=cat_str, image_url=update_doc.get("image_url", ad.get("image_url", "")), destination_url=update_doc.get("destination_url", ad.get("destination_url", "")), item_type="ad" ) await ads_collection.update_one( {"ad_id": ad_id}, {"$set": update_doc} ) invalidate_active_ads_cache() return { "success": True, "ad_id": ad_id, "message": "Campaign updated successfully" }
@router.post("/{ad_id}/status")async def set_campaign_status( ad_id: str, payload: Dict[str, Any], current_user: dict = Depends(get_current_user)): """ Pause or activate an ad campaign directly. Called by Advertiser Dashboard. """ user_id = current_user.get("uid") ad = await check_ad_ownership(ad_id, user_id) requested_status = payload.get("status", "").lower() if requested_status not in ["active", "paused", "draft"]: raise HTTPException(status_code=400, detail="Status must be 'active', 'paused', or 'draft'")
now = datetime.utcnow() if requested_status == "active": curr_status = str(ad.get("status") or "").lower() if curr_status in ("rejected", "pending", "draft"): raise HTTPException( status_code=403, detail=f"Cannot directly activate a {curr_status} campaign. Submit for moderation review." ) ad_end = ad.get("end_date") if ad_end and isinstance(ad_end, datetime): ad_end_naive = ad_end.replace(tzinfo=None) if ad_end.tzinfo else ad_end if now > ad_end_naive: raise HTTPException(status_code=400, detail="Cannot activate campaign after end date") if float(ad.get("spent", 0.0)) >= float(ad.get("budget", 0.0)): raise HTTPException(status_code=400, detail="Cannot activate campaign with exhausted budget") await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": requested_status, "updated_at": now } } ) invalidate_active_ads_cache() return { "success": True, "ad_id": ad_id, "status": requested_status, "message": f"Campaign status updated to {requested_status}" }
@router.post("/{ad_id}/submit")async def submit_for_approval( ad_id: str, current_user: dict = Depends(get_current_user)): """ Submit a draft campaign for admin approval. """ user_id = current_user.get("uid") ad = await check_ad_ownership(ad_id, user_id) if ad["status"] not in ["draft", "rejected"]: raise HTTPException( status_code=400, detail="Can only submit draft or rejected campaigns" ) now = datetime.utcnow() await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": AdStatus.PENDING.value, "submitted_at": now, "updated_at": now }, "$unset": {"rejection_reason": ""} } ) return { "success": True, "ad_id": ad_id, "status": "pending", "message": "Campaign submitted for review" }
@router.post("/{ad_id}/pause")async def pause_campaign( ad_id: str, current_user: dict = Depends(get_current_user)): """ Pause an active campaign temporarily. """ user_id = current_user.get("uid") await check_ad_ownership(ad_id, user_id) await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": AdStatus.PAUSED.value, "updated_at": datetime.utcnow() } } ) return {"success": True, "ad_id": ad_id, "status": "paused"}
@router.post("/{ad_id}/resume")async def resume_campaign( ad_id: str, current_user: dict = Depends(get_current_user)): """ Resume a paused campaign. """ user_id = current_user.get("uid") ad = await check_ad_ownership(ad_id, user_id) curr_status = str(ad.get("status") or "").lower() if curr_status != AdStatus.PAUSED.value: raise HTTPException( status_code=403, detail=f"Only paused campaigns can be resumed (current status: {curr_status or 'unknown'})." )
now = datetime.utcnow() ad_end = ad.get("end_date") if isinstance(ad_end, str) and ad_end.strip(): try: ad_end = datetime.fromisoformat(ad_end.strip().replace("Z", "+00:00")) except Exception: ad_end = None if isinstance(ad_end, datetime): ad_end_naive = ad_end.replace(tzinfo=None) if ad_end.tzinfo else ad_end if now > ad_end_naive: raise HTTPException(status_code=400, detail="Campaign end date has passed") if float(ad.get("spent", 0.0)) >= float(ad.get("budget", 0.0)): raise HTTPException(status_code=400, detail="Campaign budget exhausted") await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": AdStatus.ACTIVE.value, "updated_at": now } } ) return {"success": True, "ad_id": ad_id, "status": "active"}
@router.post("/{ad_id}/delete")@router.delete("/{ad_id}")async def delete_campaign( ad_id: str, current_user: dict = Depends(get_current_user)): """ Delete a campaign. Supports both POST and DELETE methods. """ user_id = current_user.get("uid") await check_ad_ownership(ad_id, user_id) await ads_collection.delete_one({"ad_id": ad_id}) return {"success": True, "ad_id": ad_id, "message": "Campaign deleted successfully"}
@router.get("/{ad_id}/analytics")async def get_campaign_analytics( ad_id: str, current_user: dict = Depends(get_current_user), days: int = Query(30, ge=1, le=365, description="Number of days of analytics")): """ Get detailed analytics for a specific campaign. """ user_id = current_user.get("uid") ad = await check_ad_ownership(ad_id, user_id) end_date = datetime.utcnow().date() start_date = end_date - timedelta(days=days) cursor = ad_analytics_collection.find({ "ad_id": ad_id, "date": { "$gte": start_date.isoformat(), "$lte": end_date.isoformat() } }).sort("date", 1) daily_stats = await cursor.to_list(length=days) total_impressions = int(ad.get("impressions", 0)) total_clicks = int(ad.get("clicks", 0)) total_spent = float(ad.get("spent", 0.0)) total_conversions = int(ad.get("conversions", 0)) metrics = calculate_ad_metrics(total_impressions, total_clicks, total_spent) return { "ad_id": ad_id, "title": ad.get("title"), "status": ad.get("status"), "overall": { "impressions": total_impressions, "clicks": total_clicks, "conversions": total_conversions, "spent": round(total_spent, 2), "budget": float(ad.get("budget", 0)), "ctr": metrics["ctr"], "cpc": metrics["cpc"], "conversion_rate": round((total_conversions / total_clicks * 100) if total_clicks > 0 else 0, 2) }, "daily_breakdown": [serialize_doc(s) for s in daily_stats] }
# =========================================================# ADMIN ENDPOINTS (Admin Only)# =========================================================
@router.get("/pending")async def get_pending_campaigns(admin: dict = Depends(require_admin)): """ Get all campaigns awaiting admin approval. """ cursor = ads_collection.find({"status": "pending"}).sort("submitted_at", 1) pending = await cursor.to_list(length=100) result = [] for ad in pending: advertiser = await users_collection.find_one({"uid": ad.get("advertiser_uid")}) result.append({ "id": ad.get("ad_id"), "ad_id": ad.get("ad_id"), "title": ad.get("title"), "description": ad.get("description"), "image_url": ad.get("image_url"), "destination_url": ad.get("destination_url"), "category": ad.get("category"), "budget": float(ad.get("budget", 0)), "start_date": ad.get("start_date").isoformat() if isinstance(ad.get("start_date"), datetime) else str(ad.get("start_date", "")), "end_date": ad.get("end_date").isoformat() if isinstance(ad.get("end_date"), datetime) else str(ad.get("end_date", "")), "advertiser_uid": ad.get("advertiser_uid"), "advertiser_email": ad.get("advertiser_email"), "advertiser_name": advertiser.get("displayName") or advertiser.get("username", "Unknown") if advertiser else "Unknown", "submitted_at": ad.get("submitted_at").isoformat() if isinstance(ad.get("submitted_at"), datetime) else str(ad.get("submitted_at", "")), "created_at": ad.get("created_at").isoformat() if isinstance(ad.get("created_at"), datetime) else str(ad.get("created_at", "")) }) return result
@router.post("/{ad_id}/approve")async def approve_campaign( ad_id: str, admin: dict = Depends(require_admin)): """ Approve a pending campaign (changes status to 'active'). """ ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad campaign not found") now = datetime.utcnow() await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": AdStatus.ACTIVE.value, "approved_at": now, "approved_by": admin.get("uid"), "updated_at": now } } ) return { "success": True, "ad_id": ad_id, "status": "active", "message": "Campaign approved and activated" }
@router.post("/{ad_id}/reject")async def reject_campaign( ad_id: str, rejection_data: dict, admin: dict = Depends(require_admin)): """ Reject a pending campaign with a reason. """ ad = await ads_collection.find_one({"ad_id": ad_id}) if not ad: raise HTTPException(status_code=404, detail="Ad campaign not found") reason = rejection_data.get("reason", "Does not meet our content guidelines") now = datetime.utcnow() await ads_collection.update_one( {"ad_id": ad_id}, { "$set": { "status": AdStatus.REJECTED.value, "rejected_at": now, "rejected_by": admin.get("uid"), "rejection_reason": reason, "updated_at": now } } ) return { "success": True, "ad_id": ad_id, "status": "rejected", "reason": reason }
@router.get("/stats/overview")async def get_ads_overview(admin: dict = Depends(require_admin)): """ Get overall ads system statistics for admin dashboard. """ pipeline = [ { "$group": { "_id": "$status", "count": {"$sum": 1}, "total_budget": {"$sum": "$budget"}, "total_spent": {"$sum": "$spent"} } } ] status_stats = await ads_collection.aggregate(pipeline).to_list(length=10) total_stats = await ads_collection.aggregate([ { "$group": { "_id": None, "total_impressions": {"$sum": "$impressions"}, "total_clicks": {"$sum": "$clicks"}, "total_conversions": {"$sum": "$conversions"}, "total_revenue": {"$sum": "$spent"} } } ]).to_list(length=1) return { "by_status": status_stats, "totals": total_stats[0] if total_stats else {} }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import reimport htmlimport osimport uuidimport datetimeimport loggingfrom typing import Optionalfrom pydantic import BaseModel, Fieldfrom fastapi import APIRouter, Request, HTTPException
from app.core.rate_limits import get_client_ipfrom app.limiter import limiterfrom app.database import contact_messages_collection
logger = logging.getLogger("sahihislam.contact")
router = APIRouter(tags=["Contact & Believer Support"])
EMAIL_REGEX = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")SUPPORT_EMAIL = "sahihislamsupport@gmail.com"
class ContactMessageRequest(BaseModel): fullName: str = Field(..., min_length=2, max_length=100) email: str = Field(..., min_length=5, max_length=150) subject: str = Field(..., min_length=2, max_length=100) message: str = Field(..., min_length=10, max_length=3000) honeypot: Optional[str] = Field(default="", max_length=50)
async def _handle_contact_submission(payload: ContactMessageRequest, request: Request): # 1. Anti-spam bot honeypot detection if payload.honeypot and payload.honeypot.strip(): logger.warning(f"[Contact] Bot trap triggered from IP {get_client_ip(request)}") raise HTTPException(status_code=400, detail="Automated submission rejected.")
# 2. Field sanitization & injection guards name_clean = payload.fullName.strip() email_clean = payload.email.strip().lower() subject_clean = payload.subject.strip() message_clean = payload.message.strip()
# Prevent CRLF header injection in email/subject/name for field_val, field_name in [ (name_clean, "Full Name"), (email_clean, "Email Address"), (subject_clean, "Subject"), ]: if "\r" in field_val or "\n" in field_val: raise HTTPException( status_code=400, detail=f"Invalid characters detected in {field_name}." )
# 3. Format validation if not EMAIL_REGEX.match(email_clean): raise HTTPException(status_code=400, detail="Please enter a valid email address.")
if len(message_clean) < 10: raise HTTPException(status_code=400, detail="Message is too short (minimum 10 characters).")
# 4. Generate persistent ticket ID ticket_id = f"TICK-{uuid.uuid4().hex[:8].upper()}" now = datetime.datetime.utcnow() ip = get_client_ip(request) ua = (request.headers.get("user-agent") or "")[:250]
# 5. Persist record in MongoDB email_dispatched = False try: doc = { "ticket_id": ticket_id, "fullName": name_clean, "email": email_clean, "subject": subject_clean, "message": message_clean, "status": "RECEIVED", "created_at": now, "ip": ip, "user_agent": ua, "email_dispatched": False, } await contact_messages_collection.insert_one(doc) except Exception as db_err: logger.error(f"[Contact] Failed to persist message to database: {db_err}") raise HTTPException( status_code=500, detail=f"Unable to process message due to a storage error. Please email {SUPPORT_EMAIL} directly." )
# 6. Dispatch email notification if mail credentials configured (with HTML sanitization & plain text fallback) resend_api_key = os.getenv("RESEND_API_KEY") if resend_api_key: try: import httpx name_escaped = html.escape(name_clean) subject_escaped = html.escape(subject_clean) message_escaped = html.escape(message_clean) email_escaped = html.escape(email_clean) ip_escaped = html.escape(str(ip))
mail_data = { "from": os.getenv("EMAIL_FROM", "Sahih Islam Support <noreply@sahihislam.com>"), "to": [SUPPORT_EMAIL], "reply_to": email_clean, "subject": f"[{subject_clean}] Message from {name_clean} ({ticket_id})", "text": f"Sahih Islam Support Notification\n\nTicket ID: {ticket_id}\nFrom: {name_clean} <{email_clean}>\nSubject: {subject_clean}\n\nMessage:\n{message_clean}\n\nClient IP: {ip} • Submitted at {now.isoformat()}", "html": f""" <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e2e8f0; border-radius: 8px;"> <h2 style="color: #059669;">Sahih Islam Support Notification</h2> <p><strong>Ticket ID:</strong> {ticket_id}</p> <p><strong>From:</strong> {name_escaped} (<{email_escaped}>)</p> <p><strong>Subject:</strong> {subject_escaped}</p> <hr style="border: none; border-top: 1px solid #e2e8f0; margin: 16px 0;" /> <p style="white-space: pre-wrap; color: #334155;">{message_escaped}</p> <hr style="border: none; border-top: 1px solid #e2e8f0; margin: 16px 0;" /> <p style="font-size: 12px; color: #94a3b8;">Client IP: {ip_escaped} • Submitted at {now.isoformat()}</p> </div> """ } async with httpx.AsyncClient(timeout=8.0) as client: resp = await client.post( "https://api.resend.com/emails", json=mail_data, headers={ "Authorization": f"Bearer {resend_api_key}", "Content-Type": "application/json" } ) if resp.status_code in (200, 201): email_dispatched = True await contact_messages_collection.update_one( {"ticket_id": ticket_id}, {"$set": {"email_dispatched": True}} ) except Exception as mail_err: logger.warning(f"[Contact] Email dispatch warning: {mail_err}")
# Redact email for privacy in logs (SI-SEC-017 / NEW-014) email_parts = email_clean.split("@") masked_email = f"{email_parts[0][:2]}***@{email_parts[1]}" if len(email_parts) == 2 and len(email_parts[0]) > 2 else "***@***" logger.info(f"[Contact] Successfully accepted inquiry {ticket_id} from {masked_email} (email_sent={email_dispatched})")
user_msg = ( f"JazakAllah Khair! Your message has been received. Our team will contact you shortly at {email_clean}." if email_dispatched else f"JazakAllah Khair! Your message has been recorded under ticket {ticket_id}. Our team will review it and contact you at {email_clean}." )
return { "status": "ok", "message": user_msg, "ticket_id": ticket_id, "email": email_clean, "email_dispatched": email_dispatched, }
@router.post("/contact")@limiter.limit("5/minute")async def submit_contact_form(payload: ContactMessageRequest, request: Request): return await _handle_contact_submission(payload, request)
@router.post("/api/contact")@limiter.limit("5/minute")async def submit_contact_form_api(payload: ContactMessageRequest, request: Request): return await _handle_contact_submission(payload, request)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161"""Razorpay Standard Web Checkout API RouterImplements server-authoritative order creation, price verification against trusted catalog,cryptographic signature verification, authoritative gateway capture verification,and idempotent server-side digital entitlement fulfillment.Follows Razorpay Standard Web Integration Guidelines and Sahih Islam Security Baseline."""
import osimport hmacimport hashlibfrom uuid import uuid4import loggingfrom datetime import datetime, timedeltafrom typing import Optional, Dict, Any, List
from fastapi import APIRouter, HTTPException, status, Request, Dependsfrom pydantic import BaseModel, Fieldimport httpx
try: import razorpayexcept ImportError: razorpay = None
from app.core.config import settingsfrom app.database import ( users_collection, subscriptions_collection, transactions_collection, orders_collection, wallets_collection, products_collection,)from app.limiter import limiterfrom app.payment_routes import ( fetch_razorpay_payment_api, capture_razorpay_payment_api, credit_wallet_durable_atomic, check_intro_offer_eligibility_data, CANONICAL_PLANS, RETIRED_PLANS, resolve_plan_alias,)from app.auth_deps import get_current_user, invalidate_user_cachefrom app.infrastructure.mongodb import payment_orders_collection
logger = logging.getLogger("sahihislam.razorpay_standard")
router = APIRouter(tags=["Razorpay Standard Web Checkout"])
# =========================================================# AUTHORITATIVE SERVER-SIDE PRODUCT & PRICING CATALOG# =========================================================
WEB_PRODUCT_CATALOG: Dict[str, Dict[str, Any]] = { "sahih_pro_intro_2": { "id": "sahih_pro_intro_2", "name": "First-Month Intro Special (₹2)", "amount_paise": 200, "price_inr": 2.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_pro_intro_2", "tier": "PRO", "duration_days": 30, "is_digital": True, }, "sahih_ad_free_monthly": { "id": "sahih_ad_free_monthly", "name": "Ad-Free Monthly Pass", "amount_paise": 2000, "price_inr": 20.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_ad_free_monthly", "tier": "AD_FREE_ONLY", "duration_days": 30, "is_digital": True, }, "sahih_progress_plus_monthly": { "id": "sahih_progress_plus_monthly", "name": "Progress Plus Monthly Pass", "amount_paise": 6000, "price_inr": 60.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_progress_plus_monthly", "tier": "PROGRESS_PLUS", "duration_days": 30, "is_digital": True, }, "sahih_pro_monthly": { "id": "sahih_pro_monthly", "name": "Pro Monthly Pass", "amount_paise": 15900, "price_inr": 159.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_pro_monthly", "tier": "PRO", "duration_days": 30, "is_digital": True, }, "sahih_pro_6month": { "id": "sahih_pro_6month", "name": "6-Month Pro Pass", "amount_paise": 80000, "price_inr": 800.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_pro_6month", "tier": "PRO", "duration_days": 180, "is_digital": True, }, "sahih_pro_yearly": { "id": "sahih_pro_yearly", "name": "Annual Pro Pass", "amount_paise": 150000, "price_inr": 1500.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_pro_yearly", "tier": "PRO", "duration_days": 365, "is_digital": True, }, "sahih_pro_annual": { "id": "sahih_pro_yearly", "name": "Annual Pro Pass", "amount_paise": 150000, "price_inr": 1500.0, "currency": "INR", "purpose": "subscription", "plan_id": "sahih_pro_yearly", "tier": "PRO", "duration_days": 365, "is_digital": True, }, "business_activation": { "id": "business_activation", "name": "Business Suite Activation", "amount_paise": 5000, "price_inr": 50.0, "currency": "INR", "purpose": "business_activation", "plan_id": "business_activation", "tier": "BUSINESS", "duration_days": 180, "is_digital": True, },}
PLAN_NAME_TO_PRODUCT_ID: Dict[str, str] = { "first-month intro special": "sahih_pro_intro_2", "first-month intro offer": "sahih_pro_intro_2", "first-month intro offer (₹2)": "sahih_pro_intro_2", "intro special": "sahih_pro_intro_2", "ad-free monthly pass": "sahih_ad_free_monthly", "ad-free monthly pass (₹20)": "sahih_ad_free_monthly", "ad-free basic": "sahih_ad_free_monthly", "progress plus monthly pass": "sahih_progress_plus_monthly", "pro monthly pass": "sahih_pro_monthly", "pro monthly pass (₹159)": "sahih_pro_monthly", "pro monthly": "sahih_pro_monthly", "6-month pro pass": "sahih_pro_6month", "6-month pro tier (₹800)": "sahih_pro_6month", "6-month pro pass (₹800)": "sahih_pro_6month", "annual pro pass": "sahih_pro_yearly", "annual pro pass (₹1500)": "sahih_pro_yearly", "annual pro": "sahih_pro_yearly", "business activation": "business_activation",}
# =========================================================# PYDANTIC SCHEMAS# =========================================================
class CreateOrderRequest(BaseModel): product_id: Optional[str] = Field(None, description="Authoritative catalog product ID") amount: Optional[int] = Field(None, description="Amount in paise (validated against server catalog)") currency: Optional[str] = Field("INR", description="3-letter currency code (strictly INR)") purpose: Optional[str] = Field(None, description="Order purpose: subscription, ad_wallet, shop_order, business_activation") receipt: Optional[str] = Field(None, description="Optional custom receipt ID") notes: Optional[Dict[str, Any]] = Field(default_factory=dict, description="Metadata notes") order_id: Optional[str] = Field(None, description="Marketplace order ID for physical goods") user_id: Optional[str] = Field(None, description="User UID for entitlement assignment") user_email: Optional[str] = Field(None, description="User email address")
class CreateOrderResponse(BaseModel): order_id: str amount: int currency: str key_id: Optional[str] = None receipt: Optional[str] = None product_id: Optional[str] = None purpose: Optional[str] = None
class VerifyPaymentRequest(BaseModel): razorpay_order_id: str = Field(..., description="Razorpay order identifier (order_xxx)") razorpay_payment_id: str = Field(..., description="Razorpay payment identifier (pay_xxx)") razorpay_signature: str = Field(..., description="HMAC-SHA256 signature generated by Razorpay") product_id: Optional[str] = Field(None, description="Optional product ID to reinforce entitlement resolution") user_id: Optional[str] = Field(None, description="Optional user ID for fulfillment binding") user_email: Optional[str] = Field(None, description="Optional user email for fulfillment binding")
class VerifyPaymentResponse(BaseModel): success: bool status: str fulfillment_status: str message: str order_id: Optional[str] = None payment_id: Optional[str] = None product_id: Optional[str] = None purpose: Optional[str] = None amount: Optional[float] = None entitlement_active: bool = False user_id: Optional[str] = None already_processed: bool = False
# =========================================================# HELPER FUNCTIONS# =========================================================
def _get_credentials() -> tuple[str, str]: return settings.razorpay.key_id, settings.razorpay.key_secret
def is_android_request(http_req: Optional[Request], notes: Dict[str, Any]) -> bool: """ Authoritatively determines whether a payment request originates from an Android client. Server-enforced: checks custom platform headers, User-Agent, and client notes, preventing mobile bypass by simply omitting or falsifying platform in request body. """ # 1. Explicit platform in notes or body platform_val = str(notes.get("platform") or notes.get("device_os") or "").lower().strip() if platform_val in ("android", "google_play"): return True
if not http_req: return False
# 2. Application platform headers app_platform = ( http_req.headers.get("X-App-Platform") or http_req.headers.get("X-Client-Platform") or http_req.headers.get("X-Platform") or "" ).lower().strip() if app_platform in ("android", "google_play"): return True
# 3. User-Agent inspection (Dart, Dalvik, OkHttp, Android) user_agent = (http_req.headers.get("User-Agent") or "").lower() if "dart/" in user_agent or "dalvik/" in user_agent or "okhttp/" in user_agent or "android" in user_agent: origin = http_req.headers.get("Origin") or http_req.headers.get("Referer") sec_fetch = http_req.headers.get("Sec-Fetch-Mode") or http_req.headers.get("Sec-Fetch-Site") # Distinguish browser running on Android device vs native mobile app if ("mozilla" in user_agent or "chrome" in user_agent) and (origin or sec_fetch): return False return True
return False
# =========================================================# STEP 1: CREATE ORDER ENDPOINT# =========================================================
@router.post( "/create-order", response_model=CreateOrderResponse, status_code=status.HTTP_200_OK, summary="Create Razorpay Order for Web Checkout")@router.post( "/api/create-order", response_model=CreateOrderResponse, status_code=status.HTTP_200_OK, include_in_schema=False)@limiter.limit("30/minute")async def create_order(request: Request, body: CreateOrderRequest, user: dict = Depends(get_current_user)): """ Creates a new cryptographic order on Razorpay servers. Enforces server-authoritative pricing and currency rules: 1. Currency must be strictly INR. 2. Order amounts for digital products are derived authoritatively from server catalog. 3. Client-supplied price tampering is rejected with 400. """ http_req = request payload = body key_id, key_secret = _get_credentials() if not key_id or not key_secret: logger.error("[Razorpay] Server credentials missing in environment.") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Razorpay credentials not configured on the server." )
# 1. Currency enforcement: Strictly INR currency = (payload.currency or "INR").upper().strip() if currency != "INR": raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unsupported currency '{currency}'. Web checkout strictly requires INR." )
# Minimum transaction amount enforcement (Razorpay gateway requires at least 100 paise) if payload.amount is not None and payload.amount < 100: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Order amount must be at least 100 paise (₹1 INR)." )
notes = dict(payload.notes or {}) notes.setdefault("integration", "razorpay_standard_web")
# 2. Authoritative Product & Pricing Resolution (F-01: Resolved BEFORE policy checks) candidate_pid = ( payload.product_id or notes.get("product_id") or notes.get("plan_id") ) if candidate_pid: candidate_pid = resolve_plan_alias(candidate_pid) or candidate_pid
if not candidate_pid: plan_name_raw = str(notes.get("plan_name", "")).strip().lower() if plan_name_raw in PLAN_NAME_TO_PRODUCT_ID: candidate_pid = PLAN_NAME_TO_PRODUCT_ID[plan_name_raw]
# Explicit rejection of retired plans if candidate_pid and candidate_pid in RETIRED_PLANS: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="The introductory ₹5 Pro offer has ended. Please choose one of the standard Pro plans." )
# 🛡️ RZP-01: Server-authoritative introductory offer eligibility check if candidate_pid in ("sahih_pro_intro_2", "sahih_pro_intro_5", "sahih_pro_intro"): resolved_u = user if isinstance(user, dict) else {} u_id = resolved_u.get("uid") or (getattr(http_req.state, "user_id", None) if hasattr(http_req, "state") else None) u_doc = await users_collection.find_one({"uid": u_id}) if u_id else None eligibility = check_intro_offer_eligibility_data(u_doc or {}) if not (eligibility.get("is_eligible") or eligibility.get("eligible")): reason = eligibility.get("ineligibility_reason") or eligibility.get("reason", "Account is not eligible for introductory offer.") logger.warning(f"[RazorpayStandard] Intro offer rejected for user {u_id}: {reason}") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Introductory offer unavailable: {reason}" )
# Catalog purpose resolution catalog_entry = WEB_PRODUCT_CATALOG.get(candidate_pid) if candidate_pid else None resolved_purpose = catalog_entry["purpose"] if catalog_entry else (payload.purpose or notes.get("purpose"))
# Reject client attempt to manipulate or conflict purpose with authoritative catalog if payload.purpose and catalog_entry and payload.purpose != catalog_entry["purpose"]: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Requested purpose '{payload.purpose}' conflicts with catalog product purpose '{catalog_entry['purpose']}'." )
# 🛡️ Google Play Compliance Guard (F-01): # Digital unlocks on Android (subscriptions, Business Suite activation) MUST use Google Play Billing. # Razorpay order creation for digital unlocks is strictly prohibited on Android. # Legitimate Web checkouts (sahihislamweb, Flutter Web) are permitted. is_android = is_android_request(http_req, notes) if is_android: if ( candidate_pid == "business_activation" or resolved_purpose in ("business_activation", "subscription") or (catalog_entry and catalog_entry.get("is_digital")) ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Google Play Billing is required for digital unlocks on Android. Razorpay is restricted to Web." )
purpose = resolved_purpose authoritative_amount_paise: int product_id_resolved: str = candidate_pid or ""
if candidate_pid and candidate_pid in WEB_PRODUCT_CATALOG: catalog_item = WEB_PRODUCT_CATALOG[candidate_pid] expected_amount = catalog_item["amount_paise"] if payload.amount is not None and payload.amount != expected_amount: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Price mismatch: Product '{candidate_pid}' price is {expected_amount} paise, but received {payload.amount} paise." ) authoritative_amount_paise = expected_amount purpose = catalog_item["purpose"] product_id_resolved = candidate_pid
elif purpose == "shop_order" or payload.order_id or notes.get("order_id"): shop_order_id = payload.order_id or notes.get("order_id") current_u = user if isinstance(user, dict) else {} user_id = current_u.get("uid") or getattr(payload, "user_id", None) shop_order = await orders_collection.find_one({"order_id": shop_order_id}) if not shop_order: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Shop order '{shop_order_id}' not found." ) if shop_order.get("buyer_uid") and str(shop_order.get("buyer_uid")) != str(user_id): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden: You are not authorized to purchase this order." ) expected_amount = int(round(float(shop_order.get("total", 0.0)) * 100)) if payload.amount is not None and payload.amount != expected_amount: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Price mismatch for shop order {shop_order_id}: expected {expected_amount} paise, received {payload.amount} paise." ) authoritative_amount_paise = expected_amount purpose = "shop_order" product_id_resolved = shop_order_id
elif purpose == "ad_wallet" or notes.get("purpose") == "ad_wallet": if not payload.amount or payload.amount < 100: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Ad wallet top-up requires at least 100 paise (₹1 INR)." ) authoritative_amount_paise = payload.amount purpose = "ad_wallet" product_id_resolved = "ad_wallet"
else: # Reverse match candidate by exact amount in catalog if only amount was sent matched_from_amount = None if payload.amount is not None: for pid, c_item in WEB_PRODUCT_CATALOG.items(): if c_item["amount_paise"] == payload.amount: matched_from_amount = c_item break
if matched_from_amount: authoritative_amount_paise = matched_from_amount["amount_paise"] purpose = matched_from_amount["purpose"] product_id_resolved = matched_from_amount["id"] if is_android and ( product_id_resolved == "business_activation" or purpose in ("business_activation", "subscription") or matched_from_amount.get("is_digital") ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Google Play Billing is required for digital unlocks on Android. Razorpay is restricted to Web." ) if product_id_resolved in ("sahih_pro_intro_2", "sahih_pro_intro_5", "sahih_pro_intro"): resolved_u = user if isinstance(user, dict) else {} u_id = resolved_u.get("uid") or (getattr(http_req.state, "user_id", None) if hasattr(http_req, "state") else None) u_doc = await users_collection.find_one({"uid": u_id}) if u_id else None eligibility = check_intro_offer_eligibility_data(u_doc or {}) if not (eligibility.get("is_eligible") or eligibility.get("eligible")): reason = eligibility.get("ineligibility_reason") or eligibility.get("reason", "Account is not eligible for introductory offer.") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Introductory offer unavailable: {reason}" ) else: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot create order without a recognized catalog product_id, shop order_id, or valid amount." )
receipt = payload.receipt or f"rcpt_{uuid4().hex[:12]}" current_u = user if isinstance(user, dict) else {} user_id = current_u.get("uid") or getattr(payload, "user_id", None) user_email = current_u.get("email") or payload.user_email or ""
notes["product_id"] = product_id_resolved notes["purpose"] = purpose if user_id: notes["user_id"] = str(user_id) if user_email: notes["user_email"] = str(user_email)
order_payload = { "amount": authoritative_amount_paise, "currency": "INR", "receipt": receipt, "notes": notes, "payment_capture": 1 }
# 3. Persist canonical payment order in payment_orders_collection FIRST (Fail-closed on persistence failure) now = datetime.utcnow() internal_order_id = f"pord_{uuid4().hex}" expires_at = now + timedelta(seconds=1800) try: await payment_orders_collection.insert_one({ "internal_order_id": internal_order_id, "gateway_order_id": None, "buyer_uid": str(user_id), "buyer_email": str(user_email), "amount_paise": authoritative_amount_paise, "amount_inr": authoritative_amount_paise / 100.0, "currency": "INR", "purpose": purpose, "product_id": product_id_resolved, "reference_id": product_id_resolved, "status": "created", "fulfillment_status": "pending", "idempotency_key": receipt, "created_at": now, "updated_at": now, "expires_at": expires_at, }) except Exception as db_err: logger.error(f"[Razorpay] Fatal: Failed to pre-persist canonical order record: {db_err}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Database persistence failed during order initialization. Order checkout aborted." )
# Attach internal_order_id to notes notes["internal_order_id"] = internal_order_id order_payload["notes"] = notes
# 4. Create cryptographic Razorpay Order on Gateway order_data = None if razorpay is not None: try: client = razorpay.Client(auth=(key_id, key_secret)) order_data = client.order.create(data=order_payload) logger.info(f"[Razorpay] Order created via SDK: {order_data.get('id')}") except Exception as e: logger.warning(f"[Razorpay] SDK order creation exception, attempting REST fallback: {e}")
if not order_data: try: async with httpx.AsyncClient(timeout=15.0) as http_client: resp = await http_client.post( "https://api.razorpay.com/v1/orders", auth=(key_id, key_secret), json=order_payload ) if resp.status_code == 401: await payment_orders_collection.update_one( {"internal_order_id": internal_order_id}, {"$set": {"status": "gateway_auth_failed", "updated_at": datetime.utcnow()}} ) raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Razorpay authentication failed.") if resp.status_code != 200: logger.error(f"[Razorpay] API Error {resp.status_code}: {resp.text}") await payment_orders_collection.update_one( {"internal_order_id": internal_order_id}, {"$set": {"status": "gateway_failed", "updated_at": datetime.utcnow()}} ) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Razorpay API Error: {resp.text}" ) order_data = resp.json() except HTTPException: raise except Exception as exc: logger.error(f"[Razorpay] Unexpected failure creating order: {exc}") await payment_orders_collection.update_one( {"internal_order_id": internal_order_id}, {"$set": {"status": "gateway_failed", "error": str(exc), "updated_at": datetime.utcnow()}} ) raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Failed to initialize Razorpay order: {str(exc)}" )
order_id = order_data["id"] await payment_orders_collection.update_one( {"internal_order_id": internal_order_id}, {"$set": {"gateway_order_id": order_id, "updated_at": datetime.utcnow()}} ) try: await transactions_collection.insert_one({ "transaction_id": order_id, "external_order_id": order_id, "internal_order_id": internal_order_id, "user_id": user_id, "user_email": user_email, "amount": authoritative_amount_paise / 100.0, "amount_paise": authoritative_amount_paise, "currency": "INR", "purpose": purpose, "product_id": product_id_resolved, "reference_id": product_id_resolved, "type": f"{purpose}_order", "description": f"Standard Web Order for {product_id_resolved} ({order_id})", "payment_method": "razorpay", "payment_domain": "web", "status": "created", "fulfillment_status": "pending", "notes": notes, "created_at": now, "updated_at": now, }) except Exception as db_err: logger.error(f"[Razorpay] Fatal: Failed to persist order record {order_id}: {db_err}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Database persistence failed during order initialization. Order aborted." )
return CreateOrderResponse( order_id=order_id, amount=order_data["amount"], currency=order_data["currency"], key_id=key_id, receipt=order_data.get("receipt"), product_id=product_id_resolved, purpose=purpose, )
# =========================================================# STEP 2: VERIFY PAYMENT & EXECUTE AUTHORITATIVE FULFILLMENT# =========================================================
@router.post( "/verify-payment", response_model=VerifyPaymentResponse, status_code=status.HTTP_200_OK, summary="Cryptographically Verify Razorpay HMAC-SHA256 Signature and Fulfill Entitlement")@router.post( "/api/verify-payment", response_model=VerifyPaymentResponse, status_code=status.HTTP_200_OK, include_in_schema=False)@limiter.limit("30/minute")async def verify_payment(request: Request, body: VerifyPaymentRequest): """ Verifies payment authenticity using HMAC-SHA256(order_id + '|' + payment_id, KEY_SECRET), performs authoritative gateway status check via Razorpay REST API, validates captured amount and currency, and executes idempotent server-side fulfillment for digital entitlements. """ http_req = request payload = body key_id, key_secret = _get_credentials() if not key_secret: logger.error("[Razorpay] Cannot verify signature: KEY_SECRET is not configured.") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Razorpay secret key not configured on the server." )
order_id = payload.razorpay_order_id.strip() payment_id = payload.razorpay_payment_id.strip() received_signature = payload.razorpay_signature.strip()
if not order_id or not payment_id or not received_signature: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Missing required fields: razorpay_order_id, razorpay_payment_id, razorpay_signature." )
# 1. Cryptographic HMAC-SHA256 verification signature_payload = f"{order_id}|{payment_id}".encode("utf-8") generated_signature = hmac.new( key_secret.encode("utf-8"), signature_payload, hashlib.sha256 ).hexdigest()
if not hmac.compare_digest(generated_signature, received_signature): logger.warning(f"[Razorpay] Signature mismatch for order {order_id} and payment {payment_id}!") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Payment signature verification failed. Tampered or invalid credentials." )
# 2. Look up existing order in transactions_collection for idempotency and expected details order_tx = await transactions_collection.find_one({"transaction_id": order_id}) if not order_tx: logger.warning(f"[Razorpay] Verification rejected: Order {order_id} not found in database.") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Order not found or expired. Verification cannot proceed without an authoritative persisted order record." )
if order_tx.get("fulfillment_status") == "fulfilled": logger.info(f"[Razorpay] Replay detected: order {order_id} already fulfilled.") return VerifyPaymentResponse( success=True, status="fulfilled", fulfillment_status="fulfilled", message="Payment already verified and fulfilled previously.", order_id=order_id, payment_id=payment_id, product_id=order_tx.get("product_id"), purpose=order_tx.get("purpose"), amount=order_tx.get("amount"), entitlement_active=True, user_id=order_tx.get("user_id"), already_processed=True, )
# 3. Authoritative Gateway Status Verification payment_info = await fetch_razorpay_payment_api(payment_id, key_id, key_secret) if not payment_info: logger.error(f"[Razorpay] Payment {payment_id} not found on gateway API.") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Payment verification failed: unable to fetch authoritative payment record from gateway." )
payment_status = payment_info.get("status") if payment_status == "authorized": order_amount_paise = payment_info.get("amount", 0) captured_payment = await capture_razorpay_payment_api(payment_id, order_amount_paise, key_id, key_secret) if captured_payment: payment_info = captured_payment payment_status = payment_info.get("status")
if payment_status != "captured": logger.warning(f"[Razorpay] Payment {payment_id} not captured. Status: {payment_status}") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Payment was not captured on gateway (status: {payment_status}). No benefits granted." )
# Currency validation payment_currency = payment_info.get("currency", "").upper() if payment_currency != "INR": raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid payment currency '{payment_currency}'. Expected INR." )
# Order binding check: gateway order_id MUST be present and match order_id gw_order_id = payment_info.get("order_id") if not gw_order_id or gw_order_id != order_id: logger.warning(f"[Razorpay] Gateway order mismatch: payment has order '{gw_order_id}', expected '{order_id}'") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Payment gateway order ID mismatch or missing. Payment is not bound to this order." )
# Exact amount validation against expected order amount (NEW-002 Defense) captured_amount_paise = int(payment_info.get("amount", 0)) expected_amount_paise = int(order_tx.get("amount_paise", 0)) if captured_amount_paise != expected_amount_paise: logger.warning(f"[Razorpay] Amount mismatch: captured {captured_amount_paise} paise, required {expected_amount_paise} paise.") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Amount mismatch: captured {captured_amount_paise} paise, required {expected_amount_paise} paise." )
# 4. Resolve Product & Purpose EXCLUSIVELY from Persisted Order (NEW-002 Defense) persisted_product_id = order_tx.get("product_id") if not persisted_product_id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Persisted order record has no associated product_id." )
persisted_product_id = resolve_plan_alias(persisted_product_id) or persisted_product_id
# Strictly reject client product substitution if payload.product_id: req_norm = resolve_plan_alias(payload.product_id) or payload.product_id if req_norm != persisted_product_id: logger.warning(f"[Razorpay] Product substitution attempt detected: client requested '{req_norm}', order has '{persisted_product_id}'") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Product mismatch: client requested '{payload.product_id}' but order was created for '{persisted_product_id}'. Product substitution is prohibited." )
product_id = persisted_product_id purpose = order_tx.get("purpose") or "subscription"
# Reject retired plan fulfillment if product_id in RETIRED_PLANS: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="The purchased plan is retired. Please contact support or select an active plan." )
# Replay Protection: Ensure payment_id hasn't been used on another transaction existing_pay = await transactions_collection.find_one({ "payment_id": payment_id, "transaction_id": {"$ne": order_id} }) if existing_pay: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=f"Payment ID '{payment_id}' has already been processed for another transaction." )
# 5. Resolve Identity & Fulfillment Target notes = payment_info.get("notes") or order_tx.get("notes") or {}
# Enforce User UID binding: if order already belongs to a user, a different user cannot claim it auth_uid = getattr(http_req.state, "user_id", None) if hasattr(http_req, "state") else None order_user_id = order_tx.get("user_id") if order_user_id and auth_uid and str(order_user_id) != str(auth_uid): logger.warning(f"[Razorpay] Authenticated UID mismatch: order belongs to '{order_user_id}', token UID is '{auth_uid}'") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User mismatch: this order belongs to a different authenticated user account." ) if order_user_id and payload.user_id and order_user_id != payload.user_id: logger.warning(f"[Razorpay] User mismatch: order belongs to '{order_user_id}', request claims '{payload.user_id}'") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="User mismatch: this order belongs to a different user account." )
resolved_uid = order_user_id or auth_uid or payload.user_id or notes.get("user_id") resolved_email = order_tx.get("user_email") or payload.user_email or notes.get("user_email") or payment_info.get("email")
if not resolved_uid and resolved_email: user_record = await users_collection.find_one({"email": resolved_email.strip().lower()}) if user_record: resolved_uid = user_record.get("uid")
captured_amount_inr = captured_amount_paise / 100.0 now = datetime.utcnow()
# Claim order atomically using find_one_and_update (SI-SEC-014: prevents concurrent duplicate fulfillment) lease_threshold = now - timedelta(seconds=60) claim_filter = { "transaction_id": order_id, "$or": [ {"fulfillment_status": {"$in": ["pending", "created", "failed_retryable"]}}, { "fulfillment_status": "claiming", "claim_timestamp": {"$lt": lease_threshold} } ] } claim_update = { "$set": { "fulfillment_status": "claiming", "claim_payment_id": payment_id, "claim_timestamp": now, "updated_at": now, } } claimed_order_tx = await transactions_collection.find_one_and_update( claim_filter, claim_update, return_document=False ) if not claimed_order_tx: # Check why: already fulfilled or actively being fulfilled? existing_tx = await transactions_collection.find_one({"transaction_id": order_id}) if existing_tx and existing_tx.get("fulfillment_status") == "fulfilled": logger.info(f"[Razorpay] Replay detected: order {order_id} already fulfilled.") return VerifyPaymentResponse( success=True, status="fulfilled", fulfillment_status="fulfilled", message="Payment already verified and fulfilled previously.", order_id=order_id, payment_id=payment_id, product_id=existing_tx.get("product_id"), purpose=existing_tx.get("purpose"), amount=existing_tx.get("amount"), entitlement_active=True, user_id=existing_tx.get("user_id"), already_processed=True, ) if existing_tx and existing_tx.get("fulfillment_status") == "claiming": raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="Order fulfillment is currently in progress. Please check status again shortly." ) raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail="Order is already being processed or cannot be claimed." )
entitlement_active = False
# 6. Execute Authoritative Server-Side Fulfillment under atomic claim try: if purpose == "subscription": if resolved_uid: product_cfg = WEB_PRODUCT_CATALOG.get(product_id, {}) tier = product_cfg.get("tier", "PRO") duration_days = product_cfg.get("duration_days", 30) expires_at = now + timedelta(days=duration_days)
is_pro = (tier == "PRO") is_progress_plus = (tier == "PROGRESS_PLUS") has_historical_progress = (is_pro or is_progress_plus) has_premium_themes = (is_pro or is_progress_plus) is_ad_free = True
is_intro = product_id in ("sahih_pro_intro_2", "sahih_pro_intro_5", "sahih_pro_intro") if is_intro: u_doc = await users_collection.find_one({"uid": resolved_uid}) eligibility = check_intro_offer_eligibility_data(u_doc or {}) if not (eligibility.get("is_eligible") or eligibility.get("eligible")): reason = eligibility.get("ineligibility_reason") or eligibility.get("reason", "Account is not eligible for introductory offer.") raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Introductory offer unavailable: {reason}" ) user_set_data = { "is_pro": is_pro, "is_ad_free_admob": is_ad_free, "subscription.is_pro": is_pro, "subscription.is_progress_plus": is_progress_plus, "subscription.is_ad_free_admob": is_ad_free, "subscription.has_historical_progress": has_historical_progress, "subscription.has_premium_themes": has_premium_themes, "subscription.show_sponsored_card": not is_pro, "subscription.tier": tier, "subscription.plan_id": product_id or "sahih_pro_monthly", "subscription.status": "ACTIVE", "subscription.activated_at": now, "subscription.expires_at": expires_at.isoformat(), "subscription.payment_id": payment_id, "subscription.order_id": order_id, "subscription.transaction_id": payment_id, "subscription.payment_method": "razorpay", "subscription.payment_domain": "web", "subscription.active": True, "updated_at": now, } if is_intro: user_set_data["has_claimed_intro_offer"] = True user_set_data["intro_offer_claimed_at"] = now user_set_data["subscription.has_claimed_intro_offer"] = True user_set_data["subscription.intro_offer_claimed_at"] = now.isoformat()
await users_collection.update_one( {"uid": resolved_uid}, {"$set": user_set_data} ) await invalidate_user_cache(resolved_uid)
# 🛡️ RZP-10: Atomic upsert to prevent unique index duplicate key collision on renewal/repurchase await subscriptions_collection.update_one( {"user_id": resolved_uid}, { "$set": { "plan_id": product_id or "sahih_pro_monthly", "tier": tier, "payment_id": payment_id, "order_id": order_id, "gateway": "razorpay", "amount": captured_amount_inr, "currency": "INR", "status": "active", "starts_at": now, "expires_at": expires_at, "updated_at": now, }, "$setOnInsert": {"created_at": now}, "$push": { "history": { "order_id": order_id, "payment_id": payment_id, "amount": captured_amount_inr, "created_at": now } } }, upsert=True ) entitlement_active = True logger.info(f"[Razorpay] Successfully fulfilled Pro subscription for user {resolved_uid} via order {order_id}") else: logger.warning(f"[Razorpay] Subscription purchase verified for order {order_id}, but no user UID was linked. Marked pending claim.")
elif purpose == "ad_wallet": if resolved_uid: credit_res = await credit_wallet_durable_atomic( user_id=resolved_uid, amount=captured_amount_inr, transaction_id=payment_id, description=f"Standard Web Ad Wallet Top-up ({payment_id})", payment_method="razorpay", payment_domain="web", external_order_id=order_id, ) entitlement_active = True logger.info(f"[Razorpay] Successfully credited ₹{captured_amount_inr} to wallet of user {resolved_uid}") else: logger.warning(f"[Razorpay] Ad wallet purchase verified for order {order_id}, but no user UID linked.")
elif purpose == "shop_order": shop_order_id = product_id or order_id await orders_collection.update_one( {"order_id": shop_order_id}, { "$set": { "payment_status": "paid", "status": "confirmed", "payment_id": payment_id, "updated_at": now, } } ) entitlement_active = True logger.info(f"[Razorpay] Successfully confirmed shop order {shop_order_id} via payment {payment_id}")
elif purpose == "business_activation" or product_id == "business_activation": order_notes = (claimed_order_tx.get("notes") if isinstance(claimed_order_tx, dict) else None) or order_tx.get("notes") or {} if is_android_request(http_req, order_notes): # 🛡️ Google Play Compliance Guard (F-01): Never fulfill business_activation through Razorpay on Android logger.warning(f"[Razorpay] Rejected business_activation fulfillment via Razorpay for Android order {order_id}") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Google Play Billing is required for Business Suite digital activation on Android. Razorpay fulfillment is strictly prohibited for this product on Android." )
# Legitimate Web fulfillment for Business Suite 6-Month Pass (₹50) if resolved_uid: user_doc = await users_collection.find_one({"uid": resolved_uid}) or {} curr_expires = user_doc.get("business_expires_at") or user_doc.get("business", {}).get("expires_at") base_date = now if curr_expires: if isinstance(curr_expires, str): try: curr_expires = datetime.fromisoformat(curr_expires.replace("Z", "+00:00")).replace(tzinfo=None) except Exception: curr_expires = None if isinstance(curr_expires, datetime) and curr_expires > now: base_date = curr_expires biz_expires_at = base_date + timedelta(days=180) await users_collection.update_one( {"uid": resolved_uid}, { "$set": { "is_business_enabled": True, "business_activated_at": now, "business_expires_at": biz_expires_at, "business.is_enabled": True, "business.activated_at": now, "business.expires_at": biz_expires_at, "business.is_expired": False, "updated_at": now, } } ) await invalidate_user_cache(resolved_uid) entitlement_active = True logger.info(f"[Razorpay] Successfully fulfilled Business Suite 6-month activation for web user {resolved_uid} via order {order_id}") else: logger.warning(f"[Razorpay] Business activation verified for order {order_id}, but no user UID was linked. Marked pending claim.")
# 7. Update transaction & canonical payment_order records with authoritative outcome final_fulfillment_status = "fulfilled" if entitlement_active else "pending_claim" canonical_type = "order_payment" if purpose == "shop_order" else ( "subscription_payment" if purpose == "subscription" else ( "ad_wallet_topup" if purpose == "ad_wallet" else f"{purpose}_payment" ) ) await transactions_collection.update_many( {"transaction_id": order_id}, { "$set": { "status": "completed", "fulfillment_status": final_fulfillment_status, "type": canonical_type, "reference_id": product_id, "payment_id": payment_id, "captured_amount": captured_amount_inr, "user_id": resolved_uid, "updated_at": now, } } ) try: await payment_orders_collection.update_one( {"gateway_order_id": order_id}, { "$set": { "status": "paid", "fulfillment_status": final_fulfillment_status, "payment_id": payment_id, "buyer_uid": resolved_uid, "updated_at": now, } } ) except Exception: pass except HTTPException: try: await transactions_collection.update_one( {"transaction_id": order_id}, {"$set": {"fulfillment_status": "failed_retryable", "updated_at": datetime.utcnow()}} ) await payment_orders_collection.update_one( {"gateway_order_id": order_id}, {"$set": {"fulfillment_status": "failed_retryable", "updated_at": datetime.utcnow()}} ) except Exception: pass raise except Exception as fulfill_err: logger.error(f"[Razorpay] Fulfillment error for order {order_id}: {fulfill_err}") await transactions_collection.update_one( {"transaction_id": order_id}, { "$set": { "fulfillment_status": "failed_retryable", "last_error": str(fulfill_err)[:200], "updated_at": datetime.utcnow() } } ) try: await payment_orders_collection.update_one( {"gateway_order_id": order_id}, {"$set": {"fulfillment_status": "failed_retryable", "updated_at": datetime.utcnow()}} ) except Exception: pass raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to grant entitlement. The order is recoverable and marked for retry." )
if entitlement_active: return VerifyPaymentResponse( success=True, status="fulfilled", fulfillment_status="fulfilled", message="Payment captured and digital entitlement fulfilled successfully.", order_id=order_id, payment_id=payment_id, product_id=product_id, purpose=purpose, amount=captured_amount_inr, entitlement_active=True, user_id=resolved_uid, already_processed=False, ) else: return VerifyPaymentResponse( success=True, status="paid_unfulfilled", fulfillment_status="pending_claim", message="Payment captured on gateway, but digital entitlement is pending account linking. Please sign in or contact support.", order_id=order_id, payment_id=payment_id, product_id=product_id, purpose=purpose, amount=captured_amount_inr, entitlement_active=False, user_id=None, already_processed=False, )1234567891011121314"""API v1 Router AggregatorCombines all domain feature routers under the /api/v1 prefix while keepingbackward compatibility with existing root route prefixes."""from fastapi import APIRouterfrom app.api.v1.quran import router as quran_routerfrom app.api.v1.prayer import router as prayer_router
v1_router = APIRouter(prefix="/v1")v1_router.include_router(quran_router)v1_router.include_router(prayer_router)
__all__ = ["v1_router", "quran_router", "prayer_router"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""API v1 - Prayer EndpointsThin HTTP controllers for astronomical prayer times, Qibla bearing, and geocoding."""from fastapi import APIRouter, Request, HTTPException, Queryfrom app.core.rate_limits import limiterfrom app.database import masjid_collectionfrom app.prayer_calculator import resolve_tz_offsetfrom app.services.hijri_calendar_service import HijriCalendarService, is_valid_time_strfrom app.services.prayer_service import ( compute_prayer_times, compute_additional_times, qibla_bearing, gregorian_to_hijri, geocode_address,)import datetimefrom typing import Optional
router = APIRouter(tags=["Prayer & Geolocation"])
@router.get("/prayer-context")@limiter.limit("1200/minute")async def get_prayer_context_v1( request: Request, latitude: float = Query(28.6139, ge=-90, le=90), longitude: float = Query(77.2090, ge=-180, le=180), date: Optional[str] = Query(None, description="Optional ISO date YYYY-MM-DD"), tz: Optional[float] = Query(None, ge=-14, le=14, description="Optional timezone offset in hours"), masjid_id: Optional[str] = Query(None, description="Optional linked masjid ID"), region: Optional[str] = Query(None, description="Optional region ID"), method: Optional[str] = Query("karachi", description="Calculation method preset (karachi, mwl, isna, egypt, makkah, tehran, jafari)"), is_hanafi: Optional[bool] = Query(True, description="Hanafi Asr shadow ratio (True for 2x, False for 1x Standard)"), high_latitude_rule: Optional[str] = Query("angle_based", description="High-latitude policy (middle_of_the_night, seventh_of_the_night, angle_based, nearest_latitude, none)"),): """Calculates astronomical prayer times, additional times, and Qibla bearing.""" eff_tz = resolve_tz_offset(latitude, longitude, datetime.datetime.utcnow().date(), explicit_tz=tz) if date: try: target_date = datetime.date.fromisoformat(date) except ValueError: raise HTTPException(status_code=400, detail="Invalid date format. Expected YYYY-MM-DD.") else: local_tz = datetime.timezone(datetime.timedelta(hours=float(eff_tz))) target_date = datetime.datetime.now(local_tz).date() eff_tz = resolve_tz_offset(latitude, longitude, target_date, explicit_tz=tz)
clean_masjid_id = masjid_id.strip() if isinstance(masjid_id, str) and masjid_id.strip() else None clean_region = region.strip() if isinstance(region, str) and region.strip() else None m_doc = None masjid_adj = 0 temp_corr = None legacy_override = None override_base = None effective_region = clean_region if clean_masjid_id: m_doc = await masjid_collection.find_one({"masjid_id": clean_masjid_id}) if m_doc: masjid_adj = m_doc.get("hijri_adjustment", 0) effective_region = effective_region or m_doc.get("region_id") or "kashmir" temp_corr = m_doc.get("prayers", {}).get("hijri", {}).get("temporary_correction") legacy_override = m_doc.get("hijri_override") or m_doc.get("prayers", {}).get("hijri", {}).get("override") override_base = m_doc.get("prayers", {}).get("hijri", {}).get("override_base_date") or m_doc.get("override_base_date")
is_linked = bool(clean_masjid_id and m_doc) raw_mag = ( (m_doc.get("maghrib_azan") if is_valid_time_str(m_doc.get("maghrib_azan")) else None) or (m_doc.get("timings", {}).get("MAGHRIB") if is_valid_time_str(m_doc.get("timings", {}).get("MAGHRIB")) else None) ) if m_doc else None masjid_maghrib = raw_mag
pt = compute_prayer_times( latitude, longitude, target_date, tz=eff_tz, method=method or "karachi", is_hanafi=is_hanafi if is_hanafi is not None else True, high_latitude_rule=high_latitude_rule or "angle_based", )
add_times = compute_additional_times(pt, target_date) if pt else None qibla = qibla_bearing(latitude, longitude) maghrib_t = masjid_maghrib or (getattr(pt, "maghrib", None) if pt else None) hijri_res = HijriCalendarService.resolve_effective_hijri_date( gregorian_date=target_date, region_id=effective_region or "kashmir", timezone_offset_hours=eff_tz, masjid_adjustment=masjid_adj if is_linked else 0, temporary_correction=temp_corr if is_linked else None, legacy_override_string=legacy_override if is_linked else None, override_base_date=override_base if is_linked else None, maghrib_time=maghrib_t, is_linked_to_masjid=is_linked, )
return { "status": "success", "data": { "date": target_date.isoformat(), "prayer_times": pt.to_dict() if pt else None, "additional_times": add_times.to_dict() if add_times else None, "qibla_bearing": round(qibla, 1), "hijri_date": hijri_res.formatted, "hijri": hijri_res.to_dict(), "method": getattr(pt, "method", method), "is_hanafi": is_hanafi, "high_latitude_rule": getattr(pt, "high_latitude_rule", high_latitude_rule), } }
@router.get("/geocode")@limiter.limit("600/minute")async def geocode_v1(request: Request, address: str = Query(...)): """Geocodes an address or city to latitude and longitude.""" coords = await geocode_address(address) if not coords: raise HTTPException(status_code=404, detail="Location not found") return { "status": "success", "latitude": coords[0], "longitude": coords[1], }123456789101112131415161718192021222324252627282930313233"""API v1 - Quran EndpointsThin HTTP controllers for Quran Surah metadata and full Ayah retrieval."""from fastapi import APIRouter, Request, HTTPException, Responsefrom app.core.rate_limits import limiterfrom app.services.quran_service import get_all_surahs_payload, get_surah_payload
router = APIRouter(prefix="/quran", tags=["Quran"])
@router.get("/surahs")@limiter.limit("1200/minute")async def get_all_surahs_v1(request: Request): """Fetches lightweight metadata for all 114 Surahs.""" accept_encoding = request.headers.get("accept-encoding", "") use_gzip = "gzip" in accept_encoding payload_bytes, is_gzip = await get_all_surahs_payload(use_gzip=use_gzip) headers = {"Content-Encoding": "gzip"} if is_gzip else None return Response(content=payload_bytes, media_type="application/json", headers=headers)
@router.get("/surah/{surah_no}")@limiter.limit("1200/minute")async def get_surah_details_v1(request: Request, surah_no: int): """Fetches complete Surah text with pre-compressed gzip caching.""" if surah_no < 1 or surah_no > 114: raise HTTPException(status_code=400, detail="Invalid Surah number (must be 1-114)")
accept_encoding = request.headers.get("accept-encoding", "") use_gzip = "gzip" in accept_encoding payload_bytes, is_gzip = await get_surah_payload(surah_no, use_gzip=use_gzip) headers = {"Content-Encoding": "gzip"} if is_gzip else None return Response(content=payload_bytes, media_type="application/json", headers=headers)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806"""Authentication and authorization dependencies for FastAPI routes.
Two dependencies are exposed:
get_current_user -> decodes the Firebase ID token from the Authorization: Bearer <jwt> header (or X-Firebase-Token), looks the user up in Mongo, and returns the user document.
require_admin -> shorthand: get_current_user + role == 'ADMIN'
Both raise 401 on missing/invalid/expired tokens and 403 oninsufficient privileges. We never echo the underlying firebase-adminexception text to the client (see audit H3).
Routes that act on a specific uid (e.g. /chat-history/{uid},/profile/{uid}) should additionally call`enforce_self_or_admin(current_user, target_uid)` to prevent IDOR(audit C1)."""import asyncioimport osimport timeimport uuidimport loggingfrom typing import Optional, Anyfrom datetime import datetime
from fastapi import Depends, Header, HTTPException, status, Requestfrom firebase_admin import auth as firebase_auth
from app.database import users_collection
logger = logging.getLogger("sahihislam.auth_deps")logger.setLevel(logging.INFO)
from app.core.security import extract_bearer_token as _extract_bearer_tokenfrom app.infrastructure.firebase import verify_firebase_token as _verify_token
import jsonimport timefrom typing import Tuplefrom collections import OrderedDictfrom app.redis_client import redis_managerfrom app.core.config import settings
_MEM_USER_CACHE: OrderedDict = OrderedDict()_MEM_USER_TTL = 5.0 # seconds; role changes also actively invalidate this cache_MAX_USER_CACHE = 5000 # Cap cache entries to prevent memory exhaustion
def _set_mem_user_cache(uid: str, entry: tuple): if len(_MEM_USER_CACHE) >= _MAX_USER_CACHE: _MEM_USER_CACHE.popitem(last=False) _MEM_USER_CACHE[uid] = entry
async def invalidate_user_cache(uid: str): """Invalidate cached user document on profile, role, or tier update.""" if uid: _MEM_USER_CACHE.pop(uid, None) try: await redis_manager.delete(f"auth_user:{uid}") except Exception: pass
def _make_synthetic_user(uid: str) -> dict: clean_uid = uid.strip() if uid and uid.strip() else f"test_{uuid.uuid4().hex[:8]}" # SI-SEC-006: Synthetic non-production users MUST NEVER be granted administrative or elevated roles return { "uid": clean_uid, "username": f"Persona {clean_uid[-8:]}", "primary_email": f"{clean_uid}@sahihislam.local", "email": f"{clean_uid}@sahihislam.local", "role": "USER", "is_pro": True, "is_vip": False, "is_admin": False, "is_superadmin": False, "followed_masjids": ["M-DELHI01"], "managed_masjid_id": "", "masjid_status": "NONE", "mufti_status": "NONE", "profile": {"location": "Delhi", "phone": "+919999999999"}, "_verified_token_email": f"{clean_uid}@sahihislam.local", "_verified_token_uid": clean_uid, }
DEFAULT_SUPERADMIN_EMAILS = { "admin@sahihislam.com", "zainshafibhat@gmail.com", "suhaileng.bhat@gmail.com", "zainshafibhat2@gmail.com",}
def is_superadmin_email(email: Optional[str]) -> bool: """Returns True if the email is an authoritative SuperAdmin by code whitelist or environment.""" if not email: return False clean = email.strip().lower() whitelist = set(DEFAULT_SUPERADMIN_EMAILS) whitelist.update(getattr(settings, "SUPERADMIN_EMAILS", set())) env_emails = os.getenv("SUPERADMIN_EMAILS", "") for e in env_emails.split(","): c = e.strip().lower() if c: whitelist.add(c) return clean in whitelist
def is_superadmin_uid(uid: Optional[str]) -> bool: """Returns True if the UID is an authoritative SuperAdmin by immutable UID allowlist.""" if not uid: return False clean = str(uid).strip() if not clean: return False bootstrap_uid = "" if hasattr(settings, "security") and hasattr(settings.security, "bootstrap_admin_uid"): bootstrap_uid = (settings.security.bootstrap_admin_uid or "").strip() if not bootstrap_uid: bootstrap_uid = os.getenv("BOOTSTRAP_ADMIN_UID", "").strip() if bootstrap_uid and clean == bootstrap_uid: return True
whitelist = set() if hasattr(settings, "SUPERADMIN_UIDS"): whitelist.update(settings.SUPERADMIN_UIDS) env_uids = os.getenv("SUPERADMIN_UIDS", "") for u in env_uids.split(","): c = u.strip() if c: whitelist.add(c) return clean in whitelist
async def _load_user(uid: str, email: Optional[str] = None, email_verified: bool = False) -> dict:
if ( not settings.IS_PROD and not settings.IS_STAGING and (os.getenv("TEST_MODE") == "1" or os.getenv("ALLOW_LOAD_TEST_AUTH") == "1") and any(uid.lower().startswith(p) for p in ("mock", "test", "locust", "dev", "sim")) ): return _make_synthetic_user(uid)
now_m = time.monotonic() mem_hit = _MEM_USER_CACHE.get(uid) if mem_hit and (now_m - mem_hit[0]) < _MEM_USER_TTL: _MEM_USER_CACHE.move_to_end(uid) return mem_hit[1]
cache_key = f"auth_user:{uid}" try: cached = await redis_manager.get(cache_key) if cached: user = json.loads(cached) _set_mem_user_cache(uid, (now_m, user)) return user except Exception as e: logger.debug(f"[AUTH_CACHE] Cache read error: {e}")
# 1. Primary lookup by UID only (account linking must happen via explicit linking endpoints, not implicit read-time mutation) user = await users_collection.find_one({"uid": uid})
# 4. Staff Employee Auto-Provisioning: # If the user is an active employee in staff_permissions, provision their user doc. if not user: try: from app.infrastructure.mongodb import db_admin staff_col = db_admin["staff_permissions"] staff_doc = await staff_col.find_one({ "$or": [{"uid": uid}] if not (clean_email and email_verified) else [{"uid": uid}, {"email": clean_email}], "is_active": True }) if staff_doc: logger.info(f"[STAFF AUTO-PROVISION] Provisioning verified staff member {clean_email or uid}") staff_user = { "uid": uid, "email": clean_email or staff_doc.get("email", ""), "primary_email": clean_email or staff_doc.get("email", ""), "name": staff_doc.get("name", "Staff Member"), "role": "STAFF", "is_staff": True, "is_superadmin": False, "status": "ACTIVE", "created_at": datetime.utcnow().isoformat(), "updated_at": datetime.utcnow().isoformat(), } try: await users_collection.update_one( {"$or": [{"uid": uid}, {"email": staff_user["email"]}]}, {"$set": staff_user}, upsert=True ) except Exception as e: logger.warning(f"Could not persist staff doc in Mongo: {e}") user = staff_user except Exception as err: logger.debug(f"Staff permission check in _load_user error: {err}")
if not user: # Token is valid but we have no Mongo record — the user hasn't # completed signup yet. Return 401, not 403, so the client # knows to re-run the signup flow. raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Account not provisioned; complete signup first", )
_set_mem_user_cache(uid, (now_m, user))
# Cache user document for 60 seconds to slash repetitive Mongo lookups try: user_copy = dict(user) if "_id" in user_copy: user_copy["_id"] = str(user_copy["_id"]) await redis_manager.set(cache_key, json.dumps(user_copy, default=str), expire_seconds=60) except Exception as e: logger.debug(f"[AUTH_CACHE] Cache write error: {e}")
return user
async def get_current_user( request: Request = None, authorization: Optional[str] = Header(default=None), x_firebase_token: Optional[str] = Header(default=None, alias="X-Firebase-Token"), x_user_id: Optional[str] = Header(default=None, alias="X-User-ID"), x_load_test_request_id: Optional[str] = Header(default=None, alias="X-Load-Test-Request-ID"),) -> dict: """ FastAPI dependency: extract + verify the Firebase ID token, return the corresponding Mongo user document. Use on every authenticated route. Supports synthetic test identities (Locust, mock personas, dev tokens) seamlessly in local development / load-testing mode. """ t_auth_start = time.perf_counter()
req_path = (request.url.path if request and hasattr(request, "url") and hasattr(request.url, "path") else "").lower() is_privileged_route = any( req_path.startswith(p) for p in ("/admin", "/superadmin", "/mufti", "/masjid", "/payment/platform-bank", "/payment", "/staff", "/shop/admin", "/auth", "/user/admin") )
if settings.IS_PROD or settings.IS_STAGING or settings.APP_ENV in ("closed_testing", "internal_testing") or not getattr(settings, "ALLOW_MOCK_AUTH", False): is_synthetic_allowed = False else: is_synthetic_allowed = ( os.getenv("TEST_MODE") == "1" or os.getenv("ALLOW_LOAD_TEST_AUTH") == "1" or os.getenv("ALLOW_SYNTHETIC_AUTH") == "1" or getattr(settings, "ALLOW_MOCK_AUTH", False) )
if is_synthetic_allowed and not is_privileged_route: # 1. Accept synthetic user from X-User-ID header (e.g. Locust benchmark) if isinstance(x_user_id, str) and x_user_id.strip(): user = _make_synthetic_user(x_user_id.strip()) user["_auth_duration_ms"] = (time.perf_counter() - t_auth_start) * 1000.0 return user
# 2. Accept synthetic bearer tokens (e.g. Bearer test_..., Bearer locust_...) raw_token = "" if isinstance(authorization, str) and authorization.lower().startswith("bearer "): raw_token = authorization.split(" ", 1)[1].strip() elif isinstance(x_firebase_token, str): raw_token = x_firebase_token.strip()
if raw_token and any(raw_token.lower().startswith(p) for p in ("test", "locust", "mock", "dev", "sim")): extracted_uid = raw_token for pfx in ("mock-token-", "mock_", "mock-", "test-token-", "test_", "test-"): if extracted_uid.lower().startswith(pfx): extracted_uid = extracted_uid[len(pfx):] break target_uid = extracted_uid or raw_token # If this target matches a real user in MongoDB, load the authoritative account db_user = await users_collection.find_one({ "$or": [ {"uid": target_uid}, {"email": target_uid.lower()} ] }) if db_user: if ( db_user.get("role") in ("ADMIN", "APP_ADMIN", "SUPERADMIN", "STAFF") or db_user.get("is_admin") is True or db_user.get("is_superadmin") is True or is_superadmin_email(db_user.get("email")) ): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Synthetic authentication cannot assume administrative accounts", ) u_dict = dict(db_user) u_dict["_verified_token_email_verified"] = False u_dict["_verified_token_uid"] = u_dict.get("uid") u_dict["_verified_token_email"] = u_dict.get("email") u_dict["_auth_duration_ms"] = (time.perf_counter() - t_auth_start) * 1000.0 return u_dict
user = _make_synthetic_user(target_uid) user["_auth_duration_ms"] = (time.perf_counter() - t_auth_start) * 1000.0 return user
# 3. Only if explicitly allowed for local headless benchmark without headers: if not authorization and not x_firebase_token and os.getenv("ALLOW_UNAUTHENTICATED_SYNTHETIC_AUTH") == "1": fallback_uid = f"locust_{uuid.uuid4().hex[:8]}" user = _make_synthetic_user(fallback_uid) user["_auth_duration_ms"] = (time.perf_counter() - t_auth_start) * 1000.0 return user
# Normal production Firebase token extraction and verification (offloaded off asyncio event loop) token = _extract_bearer_token(authorization, x_firebase_token) decoded = await asyncio.to_thread(_verify_token, token) verified_email = (decoded.get("email") or "").strip().lower() verified_uid = decoded.get("uid") email_verified = (decoded.get("email_verified") is True) user = await _load_user(verified_uid, email=verified_email, email_verified=email_verified) user["_verified_token_email_verified"] = email_verified # Attach cryptographically-verified claims directly from Firebase JWT user["_verified_token_email"] = verified_email user["_verified_token_uid"] = verified_uid user["_auth_duration_ms"] = (time.perf_counter() - t_auth_start) * 1000.0
# Authoritative SuperAdmin elevation (Codex NEW-001): # Strict elevation requires either immutable UID allowlist (SUPERADMIN_UIDS, BOOTSTRAP_ADMIN_UID) # OR cryptographically verified email matching whitelist AND established SUPERADMIN/ADMIN role in DB. is_uid_super = is_superadmin_uid(verified_uid) is_email_super = bool(verified_email and email_verified and is_superadmin_email(verified_email)) db_role = user.get("role") is_db_admin = bool( user.get("superadmin") is True or user.get("is_superadmin") is True or db_role in ("SUPERADMIN", "ADMIN", "APP_ADMIN") or (user.get("auth", {}) or {}).get("is_superadmin") is True )
if is_uid_super or (is_email_super and is_db_admin): user["is_superadmin"] = True user["superadmin"] = True user["role"] = "SUPERADMIN" user["allowed_tabs"] = ["*"] user["is_staff"] = False else: if verified_email and not email_verified and is_superadmin_email(verified_email): logger.warning( f"[SECURITY ALERT] Unverified email '{verified_email}' attempted superadmin elevation for UID '{verified_uid}'" ) if not (is_uid_super or (is_email_super and is_db_admin)): user["is_superadmin"] = False user["superadmin"] = False
# Check if account is in deletion grace period or mid-deletion acc_status = user.get("account_status") if acc_status in ("deletion_pending", "deletion_processing", "deletion_failed_retryable"): path = (request.url.path if request and hasattr(request, "url") and hasattr(request.url, "path") else "").lower() if acc_status == "deletion_pending": exempt_paths = [ "/auth/account/deletion-status", "/auth/account/cancel-deletion", "/auth/logout", "/auth/verify-token", ] detail_msg = ( f"Account is scheduled for deletion on {user.get('deletion_scheduled_at')}. " "You may cancel deletion within the 7-day grace period." ) else: exempt_paths = [ "/auth/account/deletion-status", "/auth/logout", "/auth/verify-token", ] detail_msg = "Account deletion is currently being finalized and the account is locked."
if not path or not any(path.endswith(ep) or ep in path for ep in exempt_paths): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=detail_msg, headers={"X-Account-Status": str(acc_status)}, )
# CONSENT-001: Block protected routes until explicit legal consent is accepted lc = user.get("legal_consent") if isinstance(lc, dict) and lc.get("accepted") is False: path = (request.url.path if request and hasattr(request, "url") and hasattr(request.url, "path") else "").lower() consent_exempt_paths = ( "/auth/legal-consent/accept", "/auth/login", "/auth/signup", "/auth/social-login", "/auth/logout", "/auth/verify-token", "/auth/account/deletion-status", "/auth/account/cancel-deletion", "/health", ) if not any(path.endswith(ep) or ep in path for ep in consent_exempt_paths): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You must accept the Privacy Policy, Terms of Service, and Voluntary Open-Access Disclosure before accessing this resource.", headers={"X-Legal-Consent-Required": "true"}, )
if request and hasattr(request, "state"): try: request.state.user = user request.state.uid = user.get("uid") except Exception: pass
return user
async def require_admin( current_user: dict = Depends(get_current_user),) -> dict: """ FastAPI dependency: require the caller to be an ADMIN. Use on every /admin/*, /mufti/resolve, /masjid/resolve endpoint.
Promoted roles (MUFTI, MASJID_ADMIN) are NOT admins. They are scoped to their own resources only; admin endpoints must be a separate role that does not exist in the public signup flow. Superadmin override is anchored to immutable UID or verified email whitelist so direct database tampering cannot elevate unauthorized accounts. """ if current_user.get("_verified_token_email_verified") is False: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges require a verified email address", )
uid = current_user.get("_verified_token_uid") or current_user.get("uid") or "" verified_email = (current_user.get("_verified_token_email") or current_user.get("email") or "").strip().lower() email_verified = (current_user.get("_verified_token_email_verified") is True)
is_uid_super = is_superadmin_uid(uid) is_whitelisted_super = bool(verified_email and email_verified and is_superadmin_email(verified_email)) role = current_user.get("role") is_db_admin = bool( role in ("ADMIN", "APP_ADMIN", "SUPERADMIN") or current_user.get("superadmin") is True or current_user.get("is_superadmin") is True or (current_user.get("auth", {}) or {}).get("is_superadmin") is True )
if not is_uid_super and not is_whitelisted_super and not is_db_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required", ) return current_user
def is_superadmin_user(current_user: dict) -> bool: """Return True if current_user is an authoritative SUPERADMIN.""" if not current_user or current_user.get("_verified_token_email_verified") is False: return False
uid = current_user.get("_verified_token_uid") or current_user.get("uid") or "" verified_email = (current_user.get("_verified_token_email") or current_user.get("email") or "").strip().lower() email_verified = (current_user.get("_verified_token_email_verified") is True)
is_uid_super = is_superadmin_uid(uid) is_whitelisted_super = bool(verified_email and email_verified and is_superadmin_email(verified_email))
role = current_user.get("role") is_db_admin = bool( current_user.get("superadmin") is True or current_user.get("is_superadmin") is True or role in ("SUPERADMIN", "ADMIN", "APP_ADMIN") or (current_user.get("auth", {}) or {}).get("is_superadmin") is True ) return bool(is_uid_super or (is_whitelisted_super and is_db_admin))
def is_finance_or_superadmin(current_user: dict) -> bool: """ Return True only for an authoritative SUPERADMIN or an active STAFF member explicitly granted the 'finance' permission/tab. Rejects moderation ADMIN/APP_ADMIN accounts and standard users. """ if is_superadmin_user(current_user): return True if not current_user: return False role = str(current_user.get("role") or "").strip().upper() if role == "STAFF" and current_user.get("is_staff") is True: tabs = current_user.get("allowed_tabs") or [] perms = current_user.get("permissions") or [] allowed = {str(x).strip().lower() for x in [*tabs, *perms] if x} return "finance" in allowed return False
async def require_superadmin( current_user: dict = Depends(get_current_user),) -> dict: """ FastAPI dependency: require the caller to be an authoritative SUPERADMIN. Strictly restricted to immutable UID allowlist (SUPERADMIN_UIDS, BOOTSTRAP_ADMIN_UID) OR cryptographically verified whitelisted email AND an established admin/superadmin role in DB. Regular ADMIN, MUFTI, or standard USER accounts are rejected with HTTP 403. """ if current_user.get("_verified_token_email_verified") is False: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Superadmin privileges require a verified email address", ) if not is_superadmin_user(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Superadmin privileges required to access platform financial settings", ) return current_user
async def require_finance_or_superadmin( current_user: dict = Depends(get_current_user),) -> dict: """FastAPI dependency: require verified SuperAdmin or Finance staff privileges.""" if not is_finance_or_superadmin(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Finance or Superadmin privileges required", ) return current_user
async def require_verified_mufti( current_user: dict = Depends(get_current_user),) -> dict: """ FastAPI dependency: require the caller to be an APPROVED Mufti. Use on /mufti/upload-hadith (see audit C5).
Mufti status is tracked solely by `mufti_status == "APPROVED"` (the legacy `is_mufti` boolean was removed). The user's `role` is independent and untouched by approval. """ if current_user.get("mufti_status") != "APPROVED": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Verified Mufti status required", ) return current_user
async def get_optional_user( request: Request = None, authorization: Optional[str] = Header(default=None), x_firebase_token: Optional[str] = Header(default=None, alias="X-Firebase-Token"), x_user_id: Optional[str] = Header(default=None, alias="X-User-ID"), x_load_test_request_id: Optional[str] = Header(default=None, alias="X-Load-Test-Request-ID"),) -> Optional[dict]: """Returns the authenticated user dict if token is provided and valid, otherwise None without raising 401 for unauthenticated guests.""" has_auth = isinstance(authorization, str) and bool(authorization.strip()) has_token = isinstance(x_firebase_token, str) and bool(x_firebase_token.strip()) has_uid = isinstance(x_user_id, str) and bool(x_user_id.strip()) if not has_auth and not has_token and not has_uid: return None try: return await get_current_user( request=request, authorization=authorization if has_auth else None, x_firebase_token=x_firebase_token if has_token else None, x_user_id=x_user_id if has_uid else None, x_load_test_request_id=x_load_test_request_id if isinstance(x_load_test_request_id, str) else None, ) except HTTPException: raise except Exception as e: logger.debug(f"[OPTIONAL_AUTH] Optional user resolution error: {e}") return None
def enforce_self_or_admin(current_user: dict, target_uid: str) -> None: """ Call this from a route that has a uid in the path or body. The caller is allowed if their own uid matches `target_uid` OR if they are an ADMIN. Raises 403 otherwise.
Example: @router.get('/profile/{uid}') async def get_profile(uid: str, user: dict = Depends(get_current_user)): enforce_self_or_admin(user, uid) ... """ if current_user.get("uid") == target_uid: return if ( current_user.get("role") in ("ADMIN", "APP_ADMIN", "SUPERADMIN") or current_user.get("is_superadmin") is True or current_user.get("superadmin") is True ): return raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Cannot act on another user's resource", )
# Admin bootstrap: the first user to call POST /auth/admin/bootstrap# (a public, signed-in-only endpoint) is promoted to ADMIN. After the# first admin exists, that endpoint returns 409 forever, and subsequent# promotions must go through POST /auth/admin/promote (require_admin).## The env-var escape hatch below is kept for headless server-side# provisioning: if you set BOOTSTRAP_ADMIN_UID, the listed uid is# promoted on the next request that triggers this function.async def ensure_bootstrap_admin() -> None: bootstrap_uid = os.getenv("BOOTSTRAP_ADMIN_UID", "").strip() if not bootstrap_uid: return result = await users_collection.update_one( {"uid": bootstrap_uid, "role": {"$ne": "ADMIN"}}, {"$set": {"role": "ADMIN"}}, ) if result.modified_count: logger.info("auth: bootstrapped ADMIN role onto uid=%s", bootstrap_uid)
def _is_datetime_active(val: Any) -> bool: """Helper to check if an expiry timestamp (datetime, float, or ISO string) is in the future.""" if val is None: return True if isinstance(val, (int, float)): return val > time.time() if isinstance(val, str): try: clean_str = val.replace("Z", "+00:00") dt = datetime.fromisoformat(clean_str) if dt.tzinfo is not None: return dt.timestamp() > time.time() return dt > datetime.utcnow() except Exception: return False if isinstance(val, datetime): if val.tzinfo is not None: return val.timestamp() > time.time() return val > datetime.utcnow() return False
async def is_user_pro(user: Optional[dict]) -> bool: """ Server-authoritative check for active PRO or VIP entitlement. Validates user document flags and subscription subdocument against current UTC time. """ if not user or not isinstance(user, dict): return False
# 1. VIP / SuperAdmin privileges if ( user.get("role") in ["SUPERADMIN", "VIP"] or user.get("is_vip") is True or user.get("superadmin") is True ): return True
# 2. Check subscription subdocument (status revocation ALWAYS overrides stale tier flags) sub = user.get("subscription") if isinstance(sub, dict): sub_status = str(sub.get("status", "")).upper() if sub_status in ["REFUNDED", "REVOKED", "EXPIRED", "PENDING", "INACTIVE"]: return False
if sub.get("tier") in ["VIP", "ENTERPRISE"] or sub.get("is_vip") is True: return True
expires_at = sub.get("expires_at") or sub.get("renews_at") if expires_at is not None: if not _is_datetime_active(expires_at): return False
if sub.get("is_pro") is True or sub.get("tier") == "PRO": return True
# 3. Direct user document flag (with optional top-level expiry) if user.get("is_pro") is True or user.get("tier") == "PRO": if isinstance(sub, dict): sub_status = str(sub.get("status", "")).upper() if sub_status in ["REFUNDED", "REVOKED", "EXPIRED", "PENDING", "INACTIVE"]: return False if sub.get("is_pro") is False: return False expires_at = sub.get("expires_at") or sub.get("renews_at") if expires_at is not None and not _is_datetime_active(expires_at): return False return True
return False
async def require_pro(current_user: dict = Depends(get_current_user)) -> dict: """ FastAPI dependency: enforces active Sahih Islam Pro entitlement. Rejects free, unverified, or expired accounts with 403 Forbidden. """ if not await is_user_pro(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Sahih Islam Pro subscription required to access this resource", ) return current_user
async def has_user_historical_progress(user: Optional[dict]) -> bool: """ Check if user has entitlement to access historical Nimaz and Tasbeeh progress (past months). Allowed for: - Sahih Pro (all tiers including ₹5 intro offer) - Progress Plus (₹60/mo) - VIP / SuperAdmin """ if not user or not isinstance(user, dict): return False if await is_user_pro(user): return True sub = user.get("subscription") if isinstance(sub, dict): sub_status = str(sub.get("status", "")).upper() if sub_status in ["REFUNDED", "REVOKED", "EXPIRED", "PENDING", "INACTIVE"]: return False expires_at = sub.get("expires_at") or sub.get("renews_at") if expires_at is not None and not _is_datetime_active(expires_at): return False if ( sub.get("plan_id") == "sahih_progress_plus_monthly" or sub.get("tier") == "PROGRESS_PLUS" or sub.get("is_progress_plus") is True or sub.get("has_historical_progress") is True ): return True return False
async def has_user_premium_themes(user: Optional[dict]) -> bool: """ Check if user has entitlement to access premium themes. Allowed for Progress Plus (₹60/mo), Sahih Pro (all tiers), and VIP / SuperAdmin. """ return await has_user_historical_progress(user)
async def has_user_ad_free(user: Optional[dict]) -> bool: """ Check if user has standard AdMob advertisements removed. Allowed for all 5 plans and ₹5 intro offer. """ if not user or not isinstance(user, dict): return False if await is_user_pro(user): return True sub = user.get("subscription") if isinstance(sub, dict): sub_status = str(sub.get("status", "")).upper() if sub_status in ["REFUNDED", "REVOKED", "EXPIRED", "PENDING", "INACTIVE"]: return False expires_at = sub.get("expires_at") or sub.get("renews_at") if expires_at is not None and not _is_datetime_active(expires_at): return False plan_id = str(sub.get("plan_id", "")) if any(p in plan_id for p in ["ad_free", "progress_plus", "pro"]): return True if sub.get("is_ad_free_admob") is True: return True return False
async def require_historical_progress(current_user: dict = Depends(get_current_user)) -> dict: """ FastAPI dependency: enforces entitlement to view historical months of daily progress. """ if not await has_user_historical_progress(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Progress Plus (₹60/mo) or Sahih Pro subscription required to access historical months", ) return current_user
def require_entitlement(feature_key: str): """ FastAPI dependency factory: enforces entitlement for a specific premium feature key. """ async def _entitlement_checker(current_user: dict = Depends(get_current_user)) -> dict: if not await is_user_pro(current_user): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=f"Sahih Islam Pro entitlement required for feature '{feature_key}'", ) return current_user return _entitlement_checker123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599# =========================================================# ISLAMIC COMMUNITY & MARKETPLACE CONTENT MODERATION ENGINE# =========================================================# Multi-field compliance analyzer using DeepSeek-Flash and# strict Islamic marketplace guardrails.# Evaluates Title, Description, Image, Category, Speaker, and# Location individually and simultaneously flags all violating fields.# =========================================================
import osimport jsonimport loggingimport reimport urllib.parseimport socketimport ipaddressfrom typing import Optional, List, Dict, Any, Tupleimport httpxfrom fastapi import HTTPExceptionfrom app.core.config import settings
logger = logging.getLogger("sahihislam.moderation")
def get_deepseek_api_key() -> str: env_val = os.getenv("DEEPSEEK_API_KEY") if env_val is not None: return env_val.strip() return (getattr(getattr(settings, "llm", None), "deepseek_api_key", "") or "").strip()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY", "").strip()DEEPSEEK_URL = "https://api.deepseek.com/chat/completions"# Official multimodal flash model name supported by DeepSeek APIDEEPSEEK_MODEL = "deepseek-flash"
SYSTEM_COMPLIANCE_PROMPT = """You are the strict Islamic Community & Marketplace Content Compliance AI for the Sahih Islam app.Examine this submission (advertisement, marketplace product, or masjid/community event) to ensure it is 100% halal and strictly complies with Islamic moral guidelines.
PROHIBITED ITEMS & CONTENT:1. Adult / 18+ content: Nudity, pornography, erotic/sexual products, intimate wear (bras, bikinis, lingerie, underwear, thongs), escort services, provocative or revealing clothing, exposed awrah, sexualized language (e.g. 'hot girls', 'hot boys', 'sexy').2. Alcohol & Intoxicants: Wine, beer, liquor, spirits, drugs, cannabis, vape/narcotics, illicit substances.3. Pork & Prohibited Animal Products: Pork, bacon, ham, lard, swine derivatives, non-halal meat.4. Gambling, Casino & Unlawful Gain: Sports betting, poker, lucky draws, lottery, usury / interest (riba) loans.5. Shirk, Idolatry & Superstition: Idols, statues of worship, tarot cards, fortune-telling, astrology, horoscopes.6. Sectarian incitement, hate speech, violent extremism, or blasphemy.7. Category mismatches: Placing un-Islamic products under holy categories like 'Islamic Books & Quran'.
CRITICAL INSTRUCTIONS ON FIELD IDENTIFICATION:Evaluate EACH field individually and accurately:- "title": Does the title contain prohibited words, intimate wear, or sexualized terms?- "description": Does the description contain prohibited words, sexualized phrases, or violate modesty?- "category": Is the selected category inappropriate or mismatched for this item?- "image_url": Does the attached image/photo show nudity, exposed awrah, lingerie, bras, bikinis, alcohol, pork, or gambling? (IMPORTANT: A photo of a fully dressed man or woman in modest everyday clothes is completely HALAL. Do NOT flag the image unless the visual pixels themselves show haram/18+ content).- "speaker": Is the speaker or organizer prohibited?- "location": Is the venue prohibited?- "destination_url": Does the link or its redirected landing page lead to adult content, pornography, gambling, betting, casinos, usury/interest loans, alcohol, pork, or non-halal services? If so, flag "destination_url".
IF VIOLATIONS ARE FOUND:Identify ALL violating fields. If multiple fields are non-compliant, you MUST list EACH ONE in the "violations" array so the user knows exactly where the problems are.Respond ONLY with a valid JSON object matching this schema:{ "approved": true or false, "violations": [ { "field": "title" | "description" | "image_url" | "category" | "speaker" | "location" | "destination_url", "reason": "Specific, clear explanation of why this specific field violates Islamic guidelines." } ]}"""
# Fallback local regex guardrails for zero-downtime safety_FALLBACK_PATTERNS = [ ( r"\b(porn|pornography|xxx|nsfw|nude|nudity|erotic|escort|lingerie|bra|bras|bikini|bikni|bikkini|panties|underwear|thong|sexy|hot\s*girls?|hot\s*boys?|adult\s*toy|dildo|vibrator)\b", "Adult, intimate wear, or sexually provocative content is strictly prohibited under Islamic guidelines." ), ( r"\b(alcohol|vodka|whisky|whiskey|beer|wine|rum|gin|champagne|liquor|brandy|cannabis|weed|drugs|narcotics)\b", "Alcoholic beverages and intoxicants are prohibited in an Islamic platform." ), ( r"\b(pork|bacon|ham|prosciutto|lard|swine)\b", "Pork and swine-derived products are strictly prohibited (haram)." ), ( r"\b(casino|betting|gambling|lottery|poker|blackjack|roulette|slot\s*machine)\b", "Gambling, betting, and lottery activities are strictly prohibited in Islam." ), ( r"\b(tarot|horoscope|zodiac|astrology|fortune\s*telling|voodoo|black\s*magic)\b", "Astrology, tarot, and fortune-telling items are prohibited in an Islamic platform." ),]
def is_ip_restricted(ip_str: str) -> bool: """Checks whether an IP is loopback, private, link-local, multicast, reserved, or cloud metadata.""" try: ip = ipaddress.ip_address(ip_str.strip()) # Unwrap IPv4-mapped IPv6 addresses (e.g. ::ffff:127.0.0.1 or ::ffff:169.254.169.254) if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: ip = ip.ipv4_mapped return ( ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved or ip.is_unspecified or (isinstance(ip, ipaddress.IPv4Address) and str(ip).startswith("169.254.")) ) except Exception: return True
from httpcore._backends.anyio import AnyIOBackend
class PinnedNetworkBackend(AnyIOBackend): """Network backend that connects the TCP socket directly to a pre-validated safe IP while preserving Host/SNI.""" def __init__(self, pinned_host: str, pinned_ip: str): super().__init__() self.pinned_host = pinned_host.lower() self.pinned_ip = pinned_ip
async def connect_tcp(self, host: str, port: int, timeout: Optional[float] = None, local_address: Optional[str] = None, socket_options=None): target_host = self.pinned_ip if host.lower() == self.pinned_host else host return await super().connect_tcp( target_host, port, timeout=timeout, local_address=local_address, socket_options=socket_options, )
class PinnedDNSTransport(httpx.AsyncHTTPTransport): """HTTPX transport pinned to a pre-validated IP to eliminate TOCTOU DNS rebinding without monkeypatching socket.getaddrinfo.""" def __init__(self, pinned_host: str, pinned_ip: str, **kwargs): backend = PinnedNetworkBackend(pinned_host, pinned_ip) super().__init__(trust_env=False, verify=True, **kwargs) self._pool._network_backend = backend
import contextlib
@contextlib.contextmanagerdef pin_dns_resolution(host: str, pinned_ip: str): """Legacy context manager retained for backwards compatibility.""" yield
class HostValidationResult(tuple): """2-tuple (is_valid, error) with .safe_ip attribute for backwards-compatibility.""" def __new__(cls, is_valid: bool, error: Optional[str] = None, safe_ip: Optional[str] = None): instance = super().__new__(cls, (is_valid, error)) instance.safe_ip = safe_ip return instance
def validate_destination_host(hostname: str, port: Optional[int] = None) -> HostValidationResult: """ Validates destination hostname and port against localhost, private IP ranges, internal DNS, and cloud metadata. Returns: HostValidationResult(is_valid, error_message, validated_safe_ip) """ if not hostname: return HostValidationResult(False, "Destination link host cannot be empty.", None) clean_host = hostname.lower().strip() if clean_host in ("localhost", "0.0.0.0", "127.0.0.1", "::1", "::"): return HostValidationResult(False, "Destination link cannot point to localhost or loopback.", None) # Disallowed non-web ports (SSRF protection) if port is not None and port not in (80, 443): return HostValidationResult(False, f"Disallowed port '{port}'. Destination links must use standard web ports (80, 443).", None)
# Direct IP literal check try: ip = ipaddress.ip_address(clean_host) if is_ip_restricted(str(ip)): return HostValidationResult(False, "Destination link cannot point to private, loopback, or cloud metadata addresses.", None) return HostValidationResult(True, None, str(ip)) except ValueError: pass # It is a domain name
# Resolve hostname via socket to prevent DNS rebinding / private IP resolution try: addr_info = socket.getaddrinfo(clean_host, port or 80) if not addr_info: return HostValidationResult(False, "Unable to resolve destination domain.", None) safe_ip = None for item in addr_info: sockaddr = item[4] ip_str = sockaddr[0] if is_ip_restricted(ip_str): return HostValidationResult(False, f"Destination domain resolves to a restricted/internal IP address ({ip_str}).", None) if not safe_ip: safe_ip = ip_str return HostValidationResult(True, None, safe_ip) except Exception as e: return HostValidationResult(False, f"DNS resolution failed for destination domain: {str(e)}", None)
_URL_PROHIBITED_PATTERNS = [ ( r"(porn|xxx|nsfw|nude|nudity|erotic|escort|onlyfans|cams|webcam|sex|stripchat|chaturbate|xhamster|xvideos)", "Adult, pornographic, or sexually explicit website." ), ( r"(casino|betting|gambling|lottery|poker|blackjack|roulette|\bslot\b|bet365|1xbet|stake\.com|betway|parimatch|dream11|\bmpl\b|winzo)", "Gambling, sports betting, or casino platform." ), ( r"(alcohol|wine|beer|liquor|whisky|vodka|weed|cannabis|vape|narcotics)", "Alcohol, intoxicants, or illicit substances platform." ), ( r"(tinder|bumble|badoo|match\.com|dating|hookup)", "Dating or hookup application/website." ), ( r"(payday\s*loan|usury|riba|instant\s*cash\s*loan)", "Usury or high-interest lending service." )]
async def inspect_destination_url(url: Optional[str]) -> Tuple[bool, Optional[str], Dict[str, Any]]: """ Follows HTTP redirects hop-by-hop to resolve the final landing URL, domain, and landing page content. Enforces strict SSRF protections against internal IPs, cloud metadata endpoints, URL credentials, and DNS rebinding attacks via socket IP pinning. Maximum 3 hops and 64 KB response stream limit. """ clean_url = (url or "").strip() if not clean_url: return True, None, {}
try: parsed = urllib.parse.urlparse(clean_url) except Exception: return False, "Invalid destination link format.", {}
if parsed.scheme not in ["http", "https"]: return False, "Destination link must start with http:// or https://", {}
if parsed.username or parsed.password: return False, "Destination link contains prohibited authentication credentials in URL.", {}
hostname = (parsed.hostname or "").lower() port = parsed.port host_res = validate_destination_host(hostname, port) host_ok, host_err = host_res safe_ip = host_res.safe_ip if not host_ok: return False, host_err, {}
# WhatsApp link handling if hostname in ["wa.me", "api.whatsapp.com", "whatsapp.com"]: query_text = urllib.parse.unquote(clean_url).lower() for pat, reason in _URL_PROHIBITED_PATTERNS: if re.search(pat, query_text, re.IGNORECASE): return False, f"WhatsApp order link text violates guidelines: {reason}", {} return True, None, { "final_url": clean_url, "final_domain": hostname, "title": "WhatsApp Direct Order Link", "description": query_text[:200], "redirected": False }
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 SahihIslamCompliance/1.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }
current_url = clean_url final_url = clean_url final_domain = hostname page_title = "" page_desc = "" redirected = False max_redirects = 3 MAX_STREAM_BYTES = 64 * 1024 # 64 KB streaming limit (P2-NET-01)
try: for hop in range(max_redirects + 1): parsed_cur = urllib.parse.urlparse(current_url) if parsed_cur.scheme not in ["http", "https"]: return False, "Redirect destination must be http or https.", {} if parsed_cur.username or parsed_cur.password: return False, "Redirect destination contains prohibited credentials.", {} cur_host = (parsed_cur.hostname or "").lower() cur_port = parsed_cur.port cur_res = validate_destination_host(cur_host, cur_port) ok, err = cur_res pinned_ip = cur_res.safe_ip if not ok or not pinned_ip: return False, f"Redirect target blocked: {err}", {}
# Execute request with DNS pinned to validated safe IP via custom transport (no global monkeypatch) transport = PinnedDNSTransport(cur_host, pinned_ip) async with httpx.AsyncClient(transport=transport, timeout=8.0, follow_redirects=False) as client: async with client.stream("GET", current_url, headers=headers) as resp: clen = resp.headers.get("content-length") if clen and clen.isdigit() and int(clen) > 1_000_000: return False, "Destination page exceeds maximum allowed size.", {}
if resp.is_redirect: if hop >= max_redirects: return False, "Destination link exceeded maximum allowed redirects.", {} location = resp.headers.get("location") if not location: break current_url = urllib.parse.urljoin(current_url, location) redirected = True final_url = current_url final_domain = (urllib.parse.urlparse(final_url).hostname or "").lower() else: final_url = str(resp.url) final_domain = (urllib.parse.urlparse(final_url).hostname or "").lower() chunks = [] total_bytes = 0 async for chunk in resp.aiter_bytes(): chunks.append(chunk) total_bytes += len(chunk) if total_bytes >= MAX_STREAM_BYTES: break raw_bytes = b"".join(chunks)[:MAX_STREAM_BYTES] text_chunk = raw_bytes.decode("utf-8", errors="replace")
title_match = re.search(r"<title[^>]*>(.*?)</title>", text_chunk, re.IGNORECASE | re.DOTALL) if title_match: page_title = re.sub(r"\s+", " ", title_match.group(1)).strip()[:150]
meta_match = re.search(r'<meta[^>]*name=["\']description["\'][^>]*content=["\'](.*?)["\']', text_chunk, re.IGNORECASE) if meta_match: page_desc = re.sub(r"\s+", " ", meta_match.group(1)).strip()[:250] break except httpx.TimeoutException: logger.warning(f"Timeout inspecting destination url {clean_url}") if settings.IS_PROD or getattr(settings, "IS_STAGING", False): return False, "Destination link timed out during safety verification.", {} except Exception as e: logger.warning(f"Error inspecting destination url {clean_url}: {e}") if settings.IS_PROD or getattr(settings, "IS_STAGING", False): return False, "Destination link could not be verified safely.", {}
combined_landing_text = f"{clean_url} {final_url} {final_domain} {page_title} {page_desc}".lower() for pattern, reason in _URL_PROHIBITED_PATTERNS: if re.search(pattern, combined_landing_text, re.IGNORECASE): redirect_msg = f"redirects to '{final_domain}' which " if redirected else "" return False, f"Destination link {redirect_msg}promotes prohibited content: {reason}", { "final_url": final_url, "final_domain": final_domain, "title": page_title, "description": page_desc, "redirected": redirected }
return True, None, { "final_url": final_url, "final_domain": final_domain, "title": page_title, "description": page_desc, "redirected": redirected }
async def screen_submission_compliance( title: str, description: str, category: str, images: Optional[List[str]] = None, image_url: Optional[str] = None, destination_url: Optional[str] = None, speaker: Optional[str] = None, location: Optional[str] = None, item_type: str = "product",) -> Dict[str, Any]: """ Screens an ad, product, or event submission using DeepSeek-Flash, URL redirection analysis, and heuristic fallbacks. Identifies ALL offending fields simultaneously and raises HTTPException(422) if violations are detected. """ all_images = [] if image_url and image_url.strip(): all_images.append(image_url.strip()) if images: for img in images: if img and img.strip() and img.strip() not in all_images: all_images.append(img.strip())
# 1. Run local heuristic pre-check on text fields individually local_violations: List[Dict[str, str]] = []
def scan_field_text(val: Optional[str], field_name: str): if not val or not str(val).strip(): return text_clean = str(val).strip() for pattern, reason in _FALLBACK_PATTERNS: if re.search(pattern, text_clean, re.IGNORECASE): if not any(v["field"] == field_name for v in local_violations): local_violations.append({"field": field_name, "reason": reason})
scan_field_text(title, "title") scan_field_text(description, "description") scan_field_text(category, "category") if speaker: scan_field_text(speaker, "speaker") if location: scan_field_text(location, "location") if destination_url: scan_field_text(destination_url, "destination_url")
# 2. Inspect destination URL redirection and landing page url_meta: Dict[str, Any] = {} if destination_url and destination_url.strip(): url_ok, url_reason, url_meta = await inspect_destination_url(destination_url) if not url_ok and url_reason: if not any(v["field"] == "destination_url" for v in local_violations): local_violations.append({ "field": "destination_url", "reason": url_reason })
if local_violations: logger.warning(f"Submission pre-check blocked {len(local_violations)} field(s): {local_violations}") detail_errors = [ { "loc": ["body", v["field"]], "msg": v["reason"], "type": "islamic_compliance_error" } for v in local_violations ] raise HTTPException(status_code=422, detail=detail_errors)
# 3. Multimodal LLM inspection via DeepSeek-Flash effective_api_key = get_deepseek_api_key() if not effective_api_key: if settings.IS_PROD or getattr(settings, "IS_STAGING", False): logger.error("DEEPSEEK_API_KEY not configured in production; failing closed for safety.") raise HTTPException( status_code=503, detail="Content moderation service is temporarily unavailable. Please try again later." ) logger.warning("DEEPSEEK_API_KEY not configured; passing after local heuristic check.") return {"approved": True}
details_parts = [ f"SUBMISSION TYPE: {item_type.upper()}", f"TITLE: {title}", f"DESCRIPTION: {description}", f"CATEGORY: {category}", ] if speaker: details_parts.append(f"SPEAKER/ORGANIZER: {speaker}") if location: details_parts.append(f"LOCATION/VENUE: {location}") if destination_url: details_parts.append(f"DESTINATION URL: {destination_url}") if url_meta.get("redirected"): details_parts.append(f"FINAL REDIRECTED URL: {url_meta.get('final_url')} (Domain: {url_meta.get('final_domain')})") if url_meta.get("title"): details_parts.append(f"DESTINATION PAGE TITLE: {url_meta.get('title')}") if url_meta.get("description"): details_parts.append(f"DESTINATION PAGE SUMMARY: {url_meta.get('description')}")
details_parts.append("Please evaluate EACH field individually (title, description, attached image, category, destination_url) for 18+, modesty, and Islamic compliance.")
user_content_parts = [ { "type": "text", "text": "\n".join(details_parts) } ]
# Attach images (up to 2 key images to keep latency ultra-fast) for img_data in all_images[:2]: if img_data.startswith("data:image/") or img_data.startswith("http://") or img_data.startswith("https://"): user_content_parts.append({ "type": "image_url", "image_url": {"url": img_data} })
payload = { "model": DEEPSEEK_MODEL, "messages": [ {"role": "system", "content": SYSTEM_COMPLIANCE_PROMPT}, {"role": "user", "content": user_content_parts} ], "response_format": {"type": "json_object"}, "reasoning_effort": "low", "temperature": 0.0, "max_tokens": 4096 }
try: async with httpx.AsyncClient(timeout=35.0) as client: resp = await client.post( DEEPSEEK_URL, headers={"Authorization": f"Bearer {effective_api_key}"}, json=payload )
if resp.status_code == 200: raw_json = resp.json() choice = raw_json.get("choices", [{}])[0] message = choice.get("message", {}) content = message.get("content", "").strip()
if not content and "reasoning_content" in message: reasoning = message.get("reasoning_content", "") json_match = re.search(r"\{[\s\S]*?\}", reasoning) if json_match: content = json_match.group(0)
result = json.loads(content) if content else {"approved": True}
if not result.get("approved", True): raw_violations = result.get("violations") or [] # Fallback if LLM used single flagged_field if not raw_violations and result.get("flagged_field"): raw_violations = [{ "field": result.get("flagged_field"), "reason": result.get("reason") or "Violates Islamic marketplace guidelines." }]
if not raw_violations and result.get("reason"): raw_violations = [{ "field": "title", "reason": result.get("reason") }]
detail_errors = [] for v in raw_violations: f_name = "title" f_reason = "Violates Islamic community guidelines." if isinstance(v, dict): f_name = v.get("field") or "title" f_reason = v.get("reason") or f_reason elif isinstance(v, str): f_reason = v lower_v = v.lower() if any(k in lower_v for k in ["image", "banner", "creative", "photo", "picture"]): f_name = "image_url" if item_type in ["ad", "event"] else "images" elif any(k in lower_v for k in ["desc", "description"]): f_name = "description" elif any(k in lower_v for k in ["cat", "category"]): f_name = "category" elif any(k in lower_v for k in ["speaker", "organizer"]): f_name = "speaker" elif any(k in lower_v for k in ["venue", "location", "address"]): f_name = "location" elif any(k in lower_v for k in ["title", "name", "heading"]): f_name = "title" elif any(k in lower_v for k in ["url", "link", "destination"]): f_name = "destination_url" else: f_name = "title"
# Remap aliases to exact frontend field keys if f_name in ["image", "banner", "photo", "picture", "creative"]: f_name = "image_url" if item_type in ["ad", "event"] else "images" elif f_name in ["speaker_name", "organizer"]: f_name = "speaker" elif f_name in ["venue", "address"]: f_name = "location" elif f_name in ["link", "url", "destination", "target_url", "website"]: f_name = "destination_url"
if not any(e["loc"][-1] == f_name for e in detail_errors): detail_errors.append({ "loc": ["body", f_name], "msg": f_reason, "type": "islamic_compliance_error" })
if detail_errors: logger.warning(f"DeepSeek-Flash rejected {item_type} with {len(detail_errors)} violation(s)") raise HTTPException(status_code=422, detail=detail_errors)
logger.info(f"DeepSeek-Flash approved {item_type}: {title}") return result
else: logger.error(f"DeepSeek API error {resp.status_code}: {resp.text[:200]}") if settings.IS_PROD or getattr(settings, "IS_STAGING", False): raise HTTPException( status_code=503, detail="Content moderation service is temporarily unavailable. Please try again later." ) # Don't block legitimate users if API returns an error in non-prod; heuristic check already passed return {"approved": True}
except HTTPException: raise except Exception as e: logger.error(f"Content moderation exception: {e}", exc_info=True) if settings.IS_PROD or getattr(settings, "IS_STAGING", False): raise HTTPException( status_code=503, detail="Content moderation service is temporarily unavailable. Please try again later." ) # Fallback to local heuristic check result in non-prod return {"approved": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Dynamic application release & build-number resolver.
Resolves `app_version`, `latest_build_number`, and `min_required_build`from build/deployment metadata instead of hardcoded constants: 1. Environment variables (`APP_VERSION`, `APP_LATEST_BUILD_NUMBER`, `APP_MIN_REQUIRED_BUILD`) 2. Monorepo `FRONTEND/pubspec.yaml` (`version: X.Y.Z+N`) when running in workspace 3. Synced `BACKEND/RELEASE_VERSION` generated during Hugging Face / Docker deployment"""from __future__ import annotations
import osimport refrom pathlib import Pathfrom typing import Any, Dict, Optional, Tuple
_VERSION_RE = re.compile(r"^\s*version:\s*([0-9A-Za-z.\-]+)\+([0-9]+)\s*$", re.MULTILINE)_BACKEND_ROOT = Path(__file__).resolve().parents[2]_PUBSPEC_CANDIDATE = _BACKEND_ROOT.parent / "FRONTEND" / "pubspec.yaml"_RELEASE_FILE_CANDIDATE = _BACKEND_ROOT / "RELEASE_VERSION"
def parse_version_spec(raw: str) -> Optional[Tuple[str, int]]: """Parse `<semver>+<build>` into `(semver, build_int)`.""" text = (raw or "").strip() if "+" not in text: return None ver_part, _, build_part = text.partition("+") ver_part = ver_part.strip() try: build_num = int(build_part.strip()) except ValueError: return None if not ver_part or build_num < 1: return None return ver_part, build_num
def sync_release_version_file( pubspec_path: Path = _PUBSPEC_CANDIDATE, release_file_path: Path = _RELEASE_FILE_CANDIDATE,) -> Optional[Tuple[str, int]]: """Read `FRONTEND/pubspec.yaml` and write `BACKEND/RELEASE_VERSION` during build/deploy.""" if not pubspec_path.is_file(): return None content = pubspec_path.read_text(encoding="utf-8") match = _VERSION_RE.search(content) if not match: return None ver_str = match.group(1).strip() build_num = int(match.group(2).strip()) release_file_path.write_text(f"{ver_str}+{build_num}\n", encoding="utf-8") return ver_str, build_num
def get_build_release_info() -> Dict[str, Any]: """Return resolved release defaults checked from env, pubspec.yaml, or RELEASE_VERSION.""" app_version = "1.0.0" latest_build = 1
if _PUBSPEC_CANDIDATE.is_file(): try: match = _VERSION_RE.search(_PUBSPEC_CANDIDATE.read_text(encoding="utf-8")) if match: app_version = match.group(1).strip() latest_build = max(1, int(match.group(2).strip())) except Exception: pass elif _RELEASE_FILE_CANDIDATE.is_file(): try: parsed = parse_version_spec(_RELEASE_FILE_CANDIDATE.read_text(encoding="utf-8")) if parsed: app_version, latest_build = parsed except Exception: pass
env_version = (os.getenv("APP_VERSION") or "").strip() if env_version: app_version = env_version
env_latest = (os.getenv("APP_LATEST_BUILD_NUMBER") or "").strip() if env_latest: try: latest_build = max(1, int(env_latest)) except ValueError: pass
min_required = latest_build env_min = (os.getenv("APP_MIN_REQUIRED_BUILD") or "").strip() if env_min: try: min_required = max(1, int(env_min)) except ValueError: pass
return { "app_version": app_version, "latest_build_number": latest_build, "min_required_build": min_required, "display_label": f"v{app_version} (Build {latest_build})", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771"""Centralized Enterprise Secrets & Configuration Module for Sahih IslamOrganizes and validates all configuration by service:- MongoDB Database- Cloudflare R2 & Edge Proxy- Redis Caching & Rate Limiting- Firebase Authentication & Admin SDK- Google Play Developer API (In-App Purchases & Subscriptions)- Apple StoreKit & App Store Server API- Razorpay Payment Gateway- Hugging Face / Machine Learning & Inference- AdMob & AADS Ad Platform- Email & Notifications (Resend & SMTP)- Core Security, Network & Reverse Proxy Isolation"""
import osimport sysimport ipaddressimport loggingimport hashlibfrom dataclasses import dataclassfrom typing import List, Optional, Set, Dict, Anyfrom dotenv import load_dotenv
# Automatically load .env if present (root and BACKEND)load_dotenv()_backend_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))_backend_env = os.path.join(_backend_dir, ".env")if os.path.exists(_backend_env): load_dotenv(_backend_env)
logger = logging.getLogger("sahihislam.config")
def resolve_worker_count(default: int = 1) -> int: """SEC-001: Canonical worker-count resolver shared by config, rate limiter, and run.py.""" for env_var in ("WEB_WORKERS", "WEB_CONCURRENCY", "UVICORN_WORKERS"): raw = (os.getenv(env_var) or "").strip() if raw: try: return max(1, int(raw)) except ValueError as exc: raise RuntimeError(f"Invalid integer value for {env_var}: {raw!r}") from exc return default
# ==============================================================================# 1. SERVICE-SPECIFIC CONFIGURATION DATACLASSES# ==============================================================================
@dataclassclass GooglePlayConfig: """Google Play Developer API and Real-Time Developer Notifications (RTDN)""" package_name: str service_account_json: Optional[str] service_account_raw: Optional[str] webhook_secret: Optional[str] allow_mock: bool
@dataclassclass MongoConfig: """MongoDB Database Connection & Pool Architecture""" uri: str db_name: str admin_db_name: str commerce_db_name: str max_pool_size: int min_pool_size: int wait_queue_timeout_ms: int allow_dev_prod_db_connect: bool
@dataclassclass CloudflareConfig: """Cloudflare R2 Object Storage & Edge Worker Acceleration""" account_id: str r2_access_key_id: str r2_secret_access_key: str r2_bucket_name: str r2_public_domain: str worker_url: str worker_secret: str api_token: str media_url: str = ""
@dataclassclass RedisConfig: """Redis Distributed Cache & Global Rate Limiting""" url: str host: str port: int password: str db: int enable_redis_rate_limit: bool enable_rate_limit: bool
@dataclassclass FirebaseConfig: """Firebase Admin SDK & Client Auth Configuration""" credentials_path: Optional[str] credentials_raw: Optional[str] project_id: str web_api_key: Optional[str]
@dataclassclass HuggingFaceConfig: """Hugging Face Model Hub & Embedding Acceleration""" token: Optional[str]
@dataclassclass AdMobConfig: """Google AdMob Environment & AADS Ad Platform Fraud Shield""" mode: str test_device_id: str aads_security_key: str
@dataclassclass RazorpayConfig: """Razorpay Payment Gateway (Web & Mobile UPI/Cards)""" key_id: str key_secret: str webhook_secret: Optional[str]
@dataclassclass AppleConfig: """Apple App Store Server API & In-App Purchases""" key_id: Optional[str] issuer_id: Optional[str] private_key: Optional[str] private_key_path: Optional[str] bundle_id: str environment: str
@dataclassclass LLMConfig: """AI & LLM Services (Hadith Q&A, Tafseer Search, Reranking)""" deepseek_api_key: str xai_api_key: str openrouter_api_key: str cohere_api_key: str reranker_api_key: str ml_concurrency: int
@dataclassclass EmailConfig: """Email Notifications & Transactional Receipts (Resend & SMTP)""" resend_api_key: Optional[str] email_from: str smtp_host: Optional[str] smtp_port: int smtp_user: Optional[str] smtp_pass: Optional[str] smtp_from: str
@dataclassclass SecurityConfig: """Core Authentication, JWT, Superadmin & Reverse Proxy Security""" secret_key: str jwt_secret: str staff_secret_key: str superadmin_emails: Set[str] superadmin_uids: Set[str] bootstrap_admin_uid: str trusted_proxy_count: int trusted_proxy_hosts: str
# ==============================================================================# 2. MAIN CENTRALIZED SETTINGS CLASS# ==============================================================================
class Settings: """ Centralized, typed, and securely validated configuration for Sahih Islam. Provides structured namespaces (settings.mongodb, settings.razorpay, etc.) while maintaining 100% backward compatibility with legacy property access. """
DEFAULT_DEV_SECRET: str = "sahihislam_enterprise_superadmin_master_secret_2026" _DEV_DEFAULT_ALLOWED_ORIGINS = [ "http://localhost:7860", "http://localhost:8080", "http://localhost:5000", "http://localhost:3000", "http://127.0.0.1:7860", "http://127.0.0.1:8080", "http://127.0.0.1:5000", "http://127.0.0.1:3000", "http://10.171.38.101:8080", "http://10.171.38.101:7860", "http://10.171.38.101:3000", "https://sahih-islam-app.web.app", "https://sahih-islam-app.firebaseapp.com", ] ALLOWED_METHODS: List[str] = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] ALLOWED_HEADERS: List[str] = [ "Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With", "X-Firebase-Token", "Cache-Control", "Last-Event-ID", "X-Request-ID", "X-User-ID", "X-Session-ID", ]
def __init__(self): self.reload()
def reload(self) -> None: """Dynamically re-reads environment variables to support isolated testing and re-configuration.""" # 1. Environment & Server Profile _is_hf = bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces") _env = (os.getenv("APP_ENV") or "").strip().lower() if _env: self.APP_ENV = _env elif _is_hf: self.APP_ENV = "production" else: self.APP_ENV = "development"
self.IS_PROD: bool = self.APP_ENV in ("production", "prod") self.IS_STAGING: bool = self.APP_ENV in ("staging", "stage") self.IS_TESTING: bool = self.APP_ENV in ("closed_testing", "internal_testing", "testing", "test") self.IS_DEV: bool = not (self.IS_PROD or self.IS_STAGING or self.IS_TESTING)
# SEC-002: Mock authentication can ONLY be enabled in development or standalone pytest test environments, # never in production, staging, closed_testing, or internal_testing. # It must be explicitly enabled via ALLOW_MOCK_AUTH=true/1 even in dev/test, defaulting to False. _raw_allow_mock = os.getenv("ALLOW_MOCK_AUTH", "0").strip().lower() in ("1", "true", "yes", "on") if self.IS_PROD or self.IS_STAGING or self.APP_ENV in ("closed_testing", "internal_testing"): self.ALLOW_MOCK_AUTH: bool = False else: self.ALLOW_MOCK_AUTH: bool = _raw_allow_mock self.PORT: int = int((os.getenv("PORT") or os.getenv("WEB_PORT") or "7860").strip() or "7860") self.WEB_HOST: str = os.getenv("WEB_HOST", "0.0.0.0") self.WEB_WORKERS: int = resolve_worker_count()
# 2. Core Security & Authentication _secret = ( os.getenv("SECRET_KEY") or os.getenv("STAFF_SECRET_KEY") or os.getenv("JWT_SECRET_KEY") or os.getenv("JWT_SECRET") or "" ).strip() # Codex NEW-017: No cryptographic secret fallback may be derived from public deployment # metadata (SPACE_ID, usernames, etc.). Production and staging require an unpredictable secret. _effective_secret = _secret if _secret else ("" if (self.IS_PROD or self.IS_STAGING) else self.DEFAULT_DEV_SECRET) _superadmins = { e.strip().lower() for e in (os.getenv("SUPERADMIN_EMAILS", "")).split(",") if e.strip() } _superadmin_uids = {u.strip() for u in (os.getenv("SUPERADMIN_UIDS", "")).split(",") if u.strip()} self.security = SecurityConfig( secret_key=_effective_secret, jwt_secret=os.getenv("JWT_SECRET", _effective_secret).strip(), staff_secret_key=os.getenv("STAFF_SECRET_KEY", _effective_secret).strip(), superadmin_emails=_superadmins, superadmin_uids=_superadmin_uids, bootstrap_admin_uid=os.getenv("BOOTSTRAP_ADMIN_UID", "").strip(), trusted_proxy_count=max(0, int(os.getenv("TRUSTED_PROXY_COUNT", "1" if self.IS_PROD else "0"))), trusted_proxy_hosts=os.getenv("TRUSTED_PROXY_HOSTS", "127.0.0.1,::1" if self.IS_PROD else "*").strip(), )
# 3. MongoDB Configuration # Primary database is canonical sahihislam with all 114 Surahs and 24,356 Hadiths if self.IS_DEV: _default_db = "sahihislam_dev" elif self.IS_STAGING: _default_db = "sahihislam_staging" elif getattr(self, "IS_CLOSED_TESTING", False): _default_db = "sahihislam_closed_testing" else: _default_db = "sahihislam" _db_name = os.getenv("MONGODB_DB_NAME") or os.getenv("MONGO_DB_NAME", _default_db).strip() _mongo_uri = (os.getenv("MONGODB_URI") or os.getenv("MONGO_URI", "")).strip() try: _raw_max_pool = int(os.getenv("MONGODB_MAX_POOL_SIZE") or os.getenv("MONGO_MAX_POOL_SIZE", "50")) except (ValueError, TypeError): _raw_max_pool = 50 try: _raw_min_pool = int(os.getenv("MONGODB_MIN_POOL_SIZE") or os.getenv("MONGO_MIN_POOL_SIZE", "5")) except (ValueError, TypeError): _raw_min_pool = 5 try: _wait_timeout = int(os.getenv("MONGODB_WAIT_QUEUE_TIMEOUT_MS") or os.getenv("MONGO_WAIT_QUEUE_TIMEOUT_MS", "5000")) except (ValueError, TypeError): _wait_timeout = 5000
self.mongodb = MongoConfig( uri=_mongo_uri, db_name=_db_name, admin_db_name=os.getenv("MONGO_DB_ADMIN_NAME", f"{_db_name}_admin").strip(), commerce_db_name=os.getenv("MONGO_DB_COMMERCE_NAME", f"{_db_name}_commerce").strip(), max_pool_size=max(1, min(_raw_max_pool, 300)), min_pool_size=max(1, min(_raw_min_pool, _raw_max_pool)), wait_queue_timeout_ms=max(500, _wait_timeout), allow_dev_prod_db_connect=os.getenv("ALLOW_DEV_PROD_DB_CONNECT") == "1", )
# 4. Cloudflare R2 Storage & Worker Proxy _cf_account = (os.getenv("CLOUDFLARE_ACCOUNT_ID") or os.getenv("R2_ACCOUNT_ID", "")).strip() _r2_access = (os.getenv("CLOUDFLARE_R2_ACCESS_KEY_ID") or os.getenv("R2_ACCESS_KEY_ID", "")).strip() _r2_secret = (os.getenv("CLOUDFLARE_R2_SECRET_ACCESS_KEY") or os.getenv("R2_SECRET_ACCESS_KEY", "")).strip() _r2_bucket = (os.getenv("CLOUDFLARE_R2_BUCKET_NAME") or os.getenv("R2_BUCKET_NAME", "sahihislam")).strip() _r2_public = (os.getenv("CLOUDFLARE_R2_PUBLIC_DOMAIN") or os.getenv("R2_PUBLIC_DOMAIN") or os.getenv("R2_PUBLIC_URL", "")).rstrip("/") _cf_worker_url = (os.getenv("CLOUDFLARE_WORKER_URL") or os.getenv("CF_WORKER_URL", "https://api-proxy.sahihislamapp.workers.dev")).rstrip("/") _cf_media_url = (os.getenv("CLOUDFLARE_MEDIA_URL") or os.getenv("CF_MEDIA_URL") or _cf_worker_url).rstrip("/") _cf_worker_secret = (os.getenv("CLOUDFLARE_WORKER_SECRET") or os.getenv("CF_WORKER_SECRET") or os.getenv("CF_UPLOAD_SECRET", "")).strip()
self.cloudflare = CloudflareConfig( account_id=_cf_account, r2_access_key_id=_r2_access, r2_secret_access_key=_r2_secret, r2_bucket_name=_r2_bucket, r2_public_domain=_r2_public, worker_url=_cf_worker_url, worker_secret=_cf_worker_secret, api_token=os.getenv("CLOUDFLARE_API_TOKEN", "").strip(), media_url=_cf_media_url, )
# 5. Redis Caching & Rate Limiting _redis_url = os.getenv("REDIS_URL", "").strip() _redis_host = os.getenv("REDIS_HOST", "localhost").strip() _redis_port = int(os.getenv("REDIS_PORT", "6379")) _redis_pass = os.getenv("REDIS_PASSWORD", "").strip() _redis_db = int(os.getenv("REDIS_DB", "0")) if not _redis_url and _redis_host and _redis_host != "localhost" and _redis_pass: _redis_url = f"rediss://:{_redis_pass}@{_redis_host}:{_redis_port}/{_redis_db}"
_raw_redis_rl = os.getenv("ENABLE_REDIS_RATE_LIMIT") _raw_redis_rl_clean = _raw_redis_rl.strip().lower() if _raw_redis_rl is not None else "" self.redis = RedisConfig( url=_redis_url, host=_redis_host, port=_redis_port, password=_redis_pass, db=_redis_db, enable_redis_rate_limit=( _raw_redis_rl_clean in ("1", "true", "yes", "on") if _raw_redis_rl_clean else (bool(_redis_url) and (self.IS_PROD or self.IS_STAGING)) ), enable_rate_limit=os.getenv("ENABLE_RATE_LIMIT", "1").strip().lower() not in ("0", "false", "off", "no"), )
# 6. Firebase Admin & Authentication _fb_path = ( os.getenv("FIREBASE_ADMIN_CREDENTIALS") or os.getenv("FIREBASE_CREDENTIALS") or os.getenv("GOOGLE_APPLICATION_CREDENTIALS") or "" ).strip() _fb_raw = ( os.getenv("FIREBASE_JSON_STRING") or os.getenv("FIREBASE_CREDENTIALS_JSON") or "" ).strip()
self.firebase = FirebaseConfig( credentials_path=_fb_path if _fb_path else None, credentials_raw=_fb_raw if _fb_raw else None, project_id=os.getenv("FIREBASE_PROJECT_ID", "sahih-islam-app").strip(), web_api_key=os.getenv("FIREBASE_WEB_API_KEY", "").strip() or None, )
# 7. Google Play Console & In-App Purchases _gp_mock = (not self.IS_PROD) and (not self.IS_STAGING) and ((os.getenv("TEST_MODE") == "1") or (os.getenv("ALLOW_MOCK_GOOGLE_PLAY") == "1") or self.IS_DEV) self.google_play = GooglePlayConfig( package_name=os.getenv("GOOGLE_PLAY_PACKAGE_NAME", "com.sahihislam.app").strip(), service_account_json=os.getenv("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON") or _fb_path or None, service_account_raw=os.getenv("GOOGLE_PLAY_SERVICE_ACCOUNT_RAW") or _fb_raw or None, webhook_secret=(os.getenv("GOOGLE_PLAY_WEBHOOK_SECRET") or os.getenv("RTDN_SECRET") or "").strip() or None, allow_mock=_gp_mock, )
# 8. Apple StoreKit & In-App Purchases self.apple = AppleConfig( key_id=os.getenv("APPLE_KEY_ID", "").strip() or None, issuer_id=os.getenv("APPLE_ISSUER_ID", "").strip() or None, private_key=os.getenv("APPLE_PRIVATE_KEY", "").strip() or None, private_key_path=os.getenv("APPLE_PRIVATE_KEY_PATH", "").strip() or None, bundle_id=os.getenv("APPLE_BUNDLE_ID", "com.sahihislam.app").strip(), environment=os.getenv("APPLE_ENVIRONMENT", "sandbox" if not self.IS_PROD else "production").strip().lower(), )
# 9. Razorpay Payment Gateway self.razorpay = RazorpayConfig( key_id=os.getenv("RAZORPAY_KEY_ID", "").strip(), key_secret=os.getenv("RAZORPAY_KEY_SECRET", "").strip(), webhook_secret=os.getenv("RAZORPAY_WEBHOOK_SECRET", "").strip() or None, )
# 10. Hugging Face self.huggingface = HuggingFaceConfig( token=(os.getenv("HUGGINGFACE_TOKEN") or os.getenv("HF_TOKEN") or "").strip() or None, )
# 11. AdMob & AADS Ad Platform _aads_env = (os.getenv("AADS_SECURITY_KEY") or "").strip() if not _aads_env and not (self.IS_PROD or getattr(self, "IS_STAGING", False)): _aads_env = "dev-aads-signing-key-32chars-minimum-pad" self.admob = AdMobConfig( mode=os.getenv("ADMOB_MODE", "test" if not self.IS_PROD else "production").strip().lower(), test_device_id=os.getenv("ADMOB_TEST_DEVICE_ID", "").strip(), aads_security_key=_aads_env, )
# 12. Machine Learning, AI & LLM Providers try: _raw_ml = int(os.getenv("ML_CONCURRENCY", "2")) except (ValueError, TypeError): _raw_ml = 2
self.llm = LLMConfig( deepseek_api_key=os.getenv("DEEPSEEK_API_KEY", "").strip(), xai_api_key=os.getenv("XAI_API_KEY", "").strip(), openrouter_api_key=os.getenv("OPENROUTER_API_KEY", "").strip(), cohere_api_key=os.getenv("COHERE_API_KEY", "").strip(), reranker_api_key=os.getenv("RERANKER_API_KEY", "").strip(), ml_concurrency=max(1, min(_raw_ml, 16)), )
# 13. Email Notifications (Resend & SMTP) self.email = EmailConfig( resend_api_key=os.getenv("RESEND_API_KEY", "").strip() or None, email_from=os.getenv("EMAIL_FROM", "Sahih Islam <sahihislamsupport@gmail.com>").strip(), smtp_host=os.getenv("SMTP_HOST", "").strip() or None, smtp_port=int(os.getenv("SMTP_PORT", "587")), smtp_user=os.getenv("SMTP_USER", "").strip() or None, smtp_pass=(os.getenv("SMTP_PASS") or os.getenv("SMTP_PASSWORD") or "").strip() or None, smtp_from=os.getenv("SMTP_FROM", "sahihislamsupport@gmail.com").strip(), )
# Feature Flags self.ENABLE_MARKETPLACE_CHECKOUT: bool = os.getenv("ENABLE_MARKETPLACE_CHECKOUT", "0").strip().lower() in ("1", "true")
# ============================================================================== # 3. BACKWARD-COMPATIBLE ALIAS PROPERTIES # ==============================================================================
@property def SECRET_KEY(self) -> str: return self.security.secret_key
@SECRET_KEY.setter def SECRET_KEY(self, val: str): self.security.secret_key = val
@property def MONGO_URI(self) -> str: return self.mongodb.uri
@MONGO_URI.setter def MONGO_URI(self, val: str): self.mongodb.uri = val
@property def MONGO_DB_NAME(self) -> str: return self.mongodb.db_name
@MONGO_DB_NAME.setter def MONGO_DB_NAME(self, val: str): self.mongodb.db_name = val
@property def MONGO_DB_ADMIN_NAME(self) -> str: return self.mongodb.admin_db_name
@MONGO_DB_ADMIN_NAME.setter def MONGO_DB_ADMIN_NAME(self, val: str): self.mongodb.admin_db_name = val
@property def MONGO_DB_COMMERCE_NAME(self) -> str: return self.mongodb.commerce_db_name
@MONGO_DB_COMMERCE_NAME.setter def MONGO_DB_COMMERCE_NAME(self, val: str): self.mongodb.commerce_db_name = val
@property def MONGO_MAX_POOL_SIZE(self) -> int: return self.mongodb.max_pool_size
@property def MONGO_MIN_POOL_SIZE(self) -> int: return self.mongodb.min_pool_size
@property def MONGO_WAIT_QUEUE_TIMEOUT_MS(self) -> int: return self.mongodb.wait_queue_timeout_ms
@property def REDIS_URL(self) -> str: return self.redis.url
@property def ENABLE_REDIS_RATE_LIMIT(self) -> bool: return self.redis.enable_redis_rate_limit
@property def ENABLE_RATE_LIMIT(self) -> bool: return self.redis.enable_rate_limit
@property def CF_WORKER_URL(self) -> str: return self.cloudflare.worker_url
@property def CF_WORKER_SECRET(self) -> str: return self.cloudflare.worker_secret
@property def R2_ACCOUNT_ID(self) -> str: return self.cloudflare.account_id
@property def R2_ACCESS_KEY_ID(self) -> str: return self.cloudflare.r2_access_key_id
@property def R2_SECRET_ACCESS_KEY(self) -> str: return self.cloudflare.r2_secret_access_key
@property def R2_BUCKET_NAME(self) -> str: return self.cloudflare.r2_bucket_name
@property def R2_PUBLIC_DOMAIN(self) -> str: return self.cloudflare.r2_public_domain
@property def ML_CONCURRENCY(self) -> int: return self.llm.ml_concurrency
@property def DEEPSEEK_API_KEY(self) -> str: return self.llm.deepseek_api_key
@property def XAI_API_KEY(self) -> str: return self.llm.xai_api_key
@property def OPENROUTER_API_KEY(self) -> str: return self.llm.openrouter_api_key
@property def RAZORPAY_KEY_ID(self) -> str: return self.razorpay.key_id
@property def RAZORPAY_KEY_SECRET(self) -> str: return self.razorpay.key_secret
@property def RAZORPAY_WEBHOOK_SECRET(self) -> Optional[str]: return self.razorpay.webhook_secret
@property def GOOGLE_PLAY_PACKAGE_NAME(self) -> str: return self.google_play.package_name
@property def GOOGLE_PLAY_WEBHOOK_SECRET(self) -> Optional[str]: return self.google_play.webhook_secret
@property def AADS_SECURITY_KEY(self) -> str: return self.admob.aads_security_key
@property def TRUSTED_PROXY_COUNT(self) -> int: return self.security.trusted_proxy_count
@property def TRUSTED_PROXY_HOSTS(self) -> str: return self.security.trusted_proxy_hosts
@TRUSTED_PROXY_HOSTS.setter def TRUSTED_PROXY_HOSTS(self, val: str): self.security.trusted_proxy_hosts = val
@property def SUPERADMIN_EMAILS(self) -> Set[str]: return self.security.superadmin_emails
@SUPERADMIN_EMAILS.setter def SUPERADMIN_EMAILS(self, val: Set[str]): self.security.superadmin_emails = set(val)
@SUPERADMIN_EMAILS.deleter def SUPERADMIN_EMAILS(self): self.security.superadmin_emails = set()
@property def SUPERADMIN_UIDS(self) -> Set[str]: return self.security.superadmin_uids
@SUPERADMIN_UIDS.setter def SUPERADMIN_UIDS(self, val: Set[str]): self.security.superadmin_uids = set(val)
@SUPERADMIN_UIDS.deleter def SUPERADMIN_UIDS(self): self.security.superadmin_uids = set()
@property def ALLOWED_ORIGINS(self) -> List[str]: if hasattr(self, "_override_allowed_origins") and self._override_allowed_origins is not None: return self._override_allowed_origins env_origins = os.getenv("ALLOWED_ORIGINS", "").strip() if env_origins: return [o.strip() for o in env_origins.split(",") if o.strip()] if self.IS_PROD or self.IS_STAGING: # In production/staging, dev localhost/LAN origins are strictly barred by default; safe production/staging origins are used origins = ["https://sahih-islam-app.web.app", "https://sahih-islam-app.firebaseapp.com"] if bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces"): origins.extend([ "https://huggingface.co", "https://sahihislam-sahih-islam.hf.space", "https://sahihislam-superadmin.hf.space", ]) return origins if getattr(self, "IS_TESTING", False): # In internal / closed testing, allow HF space, Firebase web, and local development test clients origins = ["https://sahih-islam-app.web.app", "https://sahih-islam-app.firebaseapp.com"] if bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces"): origins.extend([ "https://huggingface.co", "https://sahihislam-sahih-islam.hf.space", "https://sahihislam-superadmin.hf.space", ]) origins.extend(self._DEV_DEFAULT_ALLOWED_ORIGINS) return origins return self._DEV_DEFAULT_ALLOWED_ORIGINS
@ALLOWED_ORIGINS.setter def ALLOWED_ORIGINS(self, val: Any): if isinstance(val, str): self._override_allowed_origins = [o.strip() for o in val.split(",") if o.strip()] else: self._override_allowed_origins = list(val)
def is_trusted_proxy(self, ip_str: Optional[str]) -> bool: """Determines whether the given socket peer IP is an authorized reverse proxy.""" if not ip_str: return False clean_ip = ip_str.strip()
if not self.IS_PROD and not self.IS_STAGING and self.security.trusted_proxy_hosts == "*": return True
trusted_items = [h.strip() for h in self.security.trusted_proxy_hosts.split(",") if h.strip()] if "*" in trusted_items: if self.IS_PROD or self.IS_STAGING: return clean_ip in ("127.0.0.1", "::1", "localhost", "testclient") return True
if clean_ip in trusted_items or (clean_ip == "testclient"): return True
try: target_ip = ipaddress.ip_address(clean_ip) for item in trusted_items: if "/" in item: if target_ip in ipaddress.ip_network(item, strict=False): return True except Exception: pass
return False
def validate(self) -> None: """ Validates critical configuration at startup with fail-closed security. Ensures production deployments have strong credentials and database isolation. """ if self.IS_PROD or self.IS_STAGING: env_name = "Production" if self.IS_PROD else "Staging" # 1. Validate Secret Key (Codex NEW-017 & NEW-019) effective_key = (self.security.secret_key or "").strip() if not effective_key or effective_key == self.DEFAULT_DEV_SECRET: raise RuntimeError(f"{env_name} deployment requires a secure, non-default SECRET_KEY") if len(effective_key) < 32: raise RuntimeError(f"{env_name} deployment requires a secure, non-default SECRET_KEY of at least 32 characters")
# 2. Validate MongoDB URI if not self.mongodb.uri or not (self.mongodb.uri.startswith("mongodb://") or self.mongodb.uri.startswith("mongodb+srv://")): raise RuntimeError(f"❌ [CONFIG] In {env_name.lower()}, a valid MONGO_URI is required.")
# 3. Validate CORS Allowed Origins origins = self.ALLOWED_ORIGINS bad = [o for o in origins if "localhost" in o or "127.0.0.1" in o or "10.171.38.101" in o] if bad: raise RuntimeError(f"{env_name} ALLOWED_ORIGINS contains non-production/local origins: {bad}")
# 4. Production Database Isolation Guard if self.IS_PROD and any(term in self.mongodb.db_name.lower() for term in ["test", "dev", "mock", "sandbox"]): raise RuntimeError(f"❌ [CONFIG] Production environment cannot use test database: '{self.mongodb.db_name}'")
# 5. Validate Staff Secret Key effective_staff = os.getenv("STAFF_SECRET_KEY") or self.security.staff_secret_key if effective_staff == self.DEFAULT_DEV_SECRET: raise RuntimeError(f"{env_name} deployment cannot use default development STAFF_SECRET_KEY")
# 6. Reverse Proxy Security Notice if self.security.trusted_proxy_hosts == "*": logger.warning(f"⚠️ [CONFIG] TRUSTED_PROXY_HOSTS is set to '*' in {env_name.lower()}. This allows header spoofing unless an edge gateway strips incoming proxy headers.")
# 7. Production Shared Redis Rate Limiting (Codex NEW-021 / SEC-001) if self.ENABLE_REDIS_RATE_LIMIT and not (self.REDIS_URL or "").strip(): raise RuntimeError(f"{env_name} deployment requires a valid REDIS_URL when ENABLE_REDIS_RATE_LIMIT=1") worker_count = resolve_worker_count() require_shared_rl = os.getenv("REQUIRE_SHARED_RATE_LIMIT", "").strip().lower() in ("1", "true", "yes", "on") if (worker_count > 1 or require_shared_rl) and (not self.ENABLE_REDIS_RATE_LIMIT or not (self.REDIS_URL or "").strip()): raise RuntimeError( f"{env_name} multi-worker or strict shared-quota deployment (workers={worker_count}) " "requires ENABLE_REDIS_RATE_LIMIT=1 and a valid REDIS_URL." )
# 8. Validate AADS Security Key (P1-ADS-01) effective_aads = (self.admob.aads_security_key or "").strip() if not effective_aads or effective_aads == self.DEFAULT_DEV_SECRET or effective_aads == "dev-aads-signing-key-32chars-minimum-pad": raise RuntimeError(f"{env_name} deployment requires a secure, non-default AADS_SECURITY_KEY") if len(effective_aads) < 32: raise RuntimeError(f"{env_name} deployment requires an AADS_SECURITY_KEY of at least 32 characters")
# Validate Admin Bootstrap requirements across environments if os.getenv("ALLOW_ADMIN_BOOTSTRAP") == "1": if not (self.security.bootstrap_admin_uid or os.getenv("BOOTSTRAP_ADMIN_UID", "").strip()): raise RuntimeError("ALLOW_ADMIN_BOOTSTRAP=1 requires BOOTSTRAP_ADMIN_UID to be configured.") else: # Non-production database isolation guard if not self.IS_PROD and not getattr(self, "IS_TESTING", False) and self.mongodb.db_name == "sahihislam" and not self.mongodb.allow_dev_prod_db_connect: if not os.getenv("MONGO_DB_NAME"): self.mongodb.db_name = "sahihislam_dev" else: raise RuntimeError( "❌ [CONFIG] Safety Guard: Non-production environment attempted to target production database 'sahihislam'. " "Use isolated database or set ALLOW_DEV_PROD_DB_CONNECT=1 if intentional." ) logger.info(f"ℹ️ [CONFIG] Running in {self.APP_ENV} mode with database '{self.mongodb.db_name}'.")
logger.info( f"✅ [CONFIG] Settings verified: env={self.APP_ENV}, db={self.mongodb.db_name}, " f"ml_concurrency={self.llm.ml_concurrency}, mongo_pool=[{self.mongodb.min_pool_size}, {self.mongodb.max_pool_size}]" )
settings = Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Media & Edge CDN JWT Issuance and Verification (HS256)
Issues short/medium-lived capability JWTs (`scope: "media:read"`) signed withthe shared JWT secret (`JWT_SECRET` / `SECRET_KEY`) so Cloudflare Workers canverify requests at the edge using Web Crypto (`crypto.subtle`) without hittingthe FastAPI origin."""
import osimport timeimport loggingfrom typing import Optional, Dict, Any
import jwtfrom fastapi import HTTPException, Request, status
from app.core.config import settings
logger = logging.getLogger("sahihislam.media_token")
MEDIA_TOKEN_SCOPE = "media:read"DEFAULT_MEDIA_TOKEN_TTL_SECONDS = 86400 # 24 hours
def _get_signing_secret() -> str: secret = ( getattr(settings.security, "jwt_secret", "") or getattr(settings, "SECRET_KEY", "") or os.getenv("JWT_SECRET", "") or os.getenv("SECRET_KEY", "") ).strip() if not secret: raise RuntimeError("Media JWT signing secret is not configured") return secret
def _get_ttl_seconds(override: Optional[int] = None) -> int: if override is not None: return max(60, min(int(override), 7 * 86400)) try: raw = int(os.getenv("MEDIA_TOKEN_TTL_SECONDS", str(DEFAULT_MEDIA_TOKEN_TTL_SECONDS))) return max(60, min(raw, 7 * 86400)) except (ValueError, TypeError): return DEFAULT_MEDIA_TOKEN_TTL_SECONDS
def issue_media_jwt( subject: str, tier: str = "guest", ttl_seconds: Optional[int] = None,) -> Dict[str, Any]: """Mint an HS256 media access JWT for Cloudflare Worker edge verification.""" secret = _get_signing_secret() ttl = _get_ttl_seconds(ttl_seconds) now = int(time.time()) exp = now + ttl payload = { "sub": str(subject).strip() or "guest:anonymous", "tier": tier, "scope": MEDIA_TOKEN_SCOPE, "iat": now, "exp": exp, } token = jwt.encode(payload, secret, algorithm="HS256") if isinstance(token, bytes): token = token.decode("utf-8") return { "token": token, "token_type": "Bearer", "expires_in": ttl, "expires_at": exp, "tier": tier, }
def verify_media_jwt(token: str) -> Dict[str, Any]: """Verify an HS256 media access JWT; raises HTTP 401 on any validation failure.""" try: secret = _get_signing_secret() except RuntimeError: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Media token verification is unavailable", )
try: payload = jwt.decode( token, secret, algorithms=["HS256"], options={"require": ["exp", "sub", "scope"]}, ) except jwt.ExpiredSignatureError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Media token expired", headers={"WWW-Authenticate": "Bearer"}, ) except jwt.InvalidTokenError: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid media token", headers={"WWW-Authenticate": "Bearer"}, )
if payload.get("scope") != MEDIA_TOKEN_SCOPE: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid media token scope", headers={"WWW-Authenticate": "Bearer"}, ) return payload
def extract_media_token(request: Optional[Request]) -> Optional[str]: """Extract Bearer header or `?token=` query parameter cleanly (unit-test safe).""" if request is None: return None
headers = getattr(request, "headers", None) if headers is not None and hasattr(headers, "get"): auth_header = headers.get("authorization") or headers.get("Authorization") if isinstance(auth_header, str) and auth_header.strip(): parts = auth_header.strip().split(None, 1) if len(parts) == 2 and parts[0].lower() == "bearer" and parts[1].strip(): return parts[1].strip()
query_params = getattr(request, "query_params", None) if query_params is not None and hasattr(query_params, "get"): q_tok = query_params.get("token") if isinstance(q_tok, str) and q_tok.strip(): return q_tok.strip()
return None
def is_media_jwt_enforced() -> bool: """When true, unauthenticated origin R2 media reads fail with HTTP 401.""" return os.getenv("ENFORCE_MEDIA_JWT", "false").strip().lower() == "true"
async def verify_media_access(request: Request, strict: bool = False) -> Optional[Dict[str, Any]]: """ FastAPI dependency for R2 media endpoints: - If a token IS provided (header or `?token=`), always verify it strictly (401 on invalid/expired). - If NO token is provided, require 401 when `strict` or `ENFORCE_MEDIA_JWT=true`; otherwise permit legacy unauthenticated app builds during the rollout window. """ token = extract_media_token(request) if token: return verify_media_jwt(token)
if strict or is_media_jwt_enforced(): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Media access token required", headers={"WWW-Authenticate": "Bearer"}, ) return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324"""
Core Rate Limiting Configuration
Provides SlowAPI Limiter instance with flexible storage (memory:// or redis://),
anti-spoofing proxy validation, and collision-resistant client identification.
"""
import os
import logging
import hashlib
import ipaddress
from urllib.parse import urlsplit
from typing import Optional
from slowapi import Limiter
from slowapi.util import get_remote_address
from app.core.config import resolve_worker_count, settings
logger = logging.getLogger("sahihislam.limiter")
def sanitize_storage_uri(uri: Optional[str]) -> str:
"""Returns scheme://host[:port] without userinfo/passwords so Redis credentials never enter logs."""
if not uri:
return "memory://"
raw = str(uri).strip()
if raw == "memory://":
return "memory://"
try:
parsed = urlsplit(raw)
if parsed.scheme and parsed.hostname:
port_part = f":{parsed.port}" if parsed.port else ""
return f"{parsed.scheme}://{parsed.hostname}{port_part}"
if parsed.scheme:
return f"{parsed.scheme}://<redacted>"
except Exception:
pass
return "<redacted>"
def _validate_ip(ip_str: Optional[str]) -> Optional[str]:
"""Validates that a string is a well-formed IPv4 or IPv6 address and returns canonical format."""
if not ip_str:
return None
cleaned = ip_str.strip()
try:
ip_obj = ipaddress.ip_address(cleaned)
return str(ip_obj)
except ValueError:
return None
def get_client_ip(request) -> str:
"""
Authoritative, spoof-resistant client IP extractor.
Only trusts proxy headers (CF-Connecting-IP, X-Real-IP, X-Forwarded-For)
if the immediate socket connection (request.client.host) originates
from a verified trusted proxy (settings.is_trusted_proxy).
"""
try:
peer_ip = request.client.host if (request.client and getattr(request.client, "host", None)) else None
if not peer_ip:
return ""
# Only trust proxy headers if the immediate socket client is a verified trusted proxy
if settings.is_trusted_proxy(peer_ip):
# 1. Cloudflare Edge IP
cf_ip = _validate_ip(request.headers.get("cf-connecting-ip") if hasattr(request, "headers") else None)
if cf_ip:
return cf_ip
# 2. Trusted Reverse Proxy IP
real_ip = _validate_ip(request.headers.get("x-real-ip") if hasattr(request, "headers") else None)
if real_ip:
return real_ip
# 3. X-Forwarded-For Chain (extract client IP)
xff = request.headers.get("x-forwarded-for") if hasattr(request, "headers") else None
if xff:
parts = [p.strip() for p in xff.split(",") if p.strip()]
for part in parts:
valid_part = _validate_ip(part)
if valid_part and not settings.is_trusted_proxy(valid_part):
return valid_part
if parts:
fallback_xff = _validate_ip(parts[0])
if fallback_xff:
return fallback_xff
# Untrusted peer or direct socket connection -> strictly return the socket peer IP
valid_peer = _validate_ip(peer_ip)
return valid_peer if valid_peer else "127.0.0.1"
except Exception as e:
logger.debug(f"[LIMITER] get_client_ip exception: {e}")
return ""
def enterprise_key_func(request) -> str:
"""
Hardened client identification key extractor for SlowAPI:
1. Authoritative Authenticated User State (request.state.user['uid'] or request.state.uid)
2. Explicit non-production load-test override ONLY in development/testing mode with ALLOW_LOAD_TEST_AUTH=1 or TEST_MODE=1.
In production and staging, caller-controlled X-User-ID and arbitrary Authorization strings are NEVER trusted.
3. Unauthenticated requests: strictly keyed by verified client IP (get_client_ip(request)).
4. Connection-isolated fallback hash if IP extraction is unavailable.
"""
try:
# 1. Authoritative Authenticated User State (set server-side by auth dependencies)
user_state = getattr(request.state, "user", None)
if isinstance(user_state, dict) and user_state.get("uid"):
return f"usr:{str(user_state['uid']).strip()}"
uid_state = getattr(request.state, "uid", None)
if uid_state and isinstance(uid_state, str) and uid_state.strip():
return f"usr:{uid_state.strip()}"
# 2. Non-production test harness ONLY:
is_prod_or_staging = settings.IS_PROD or settings.IS_STAGING
if not is_prod_or_staging and (os.getenv("TEST_MODE") == "1" or os.getenv("ALLOW_LOAD_TEST_AUTH") == "1"):
x_user = request.headers.get("x-user-id") if hasattr(request, "headers") else None
if x_user and x_user.strip():
return f"usr:{x_user.strip()}"
# 3. For all unauthenticated requests: Strictly key by verified client IP
# SI-SEC-010: Do NOT trust caller-controlled Authorization strings or X-User-ID headers,
# which would allow malicious callers to rotate headers and evade IP rate limits.
resolved_ip = get_client_ip(request)
if resolved_ip:
return f"ip:{resolved_ip}"
# 4. Connection Hash Fallback (Unique per connection context, avoiding shared starvation)
fallback_id = getattr(request, "client", None) or "anon"
conn_hash = hashlib.sha256(str(fallback_id).encode("utf-8")).hexdigest()[:12]
return f"conn:{conn_hash}"
except Exception as e:
logger.debug(f"[LIMITER] Key extraction exception: {e}")
conn_hash = hashlib.sha256(str(getattr(request, "client", "anon")).encode("utf-8")).hexdigest()[:12]
return f"conn:{conn_hash}"
def create_limiter(storage_uri: Optional[str] = None, enabled: Optional[bool] = None, fail_closed_on_redis_error: bool = False) -> Limiter:
"""
Factory creating a Limiter instance with fail-closed production protection (Codex NEW-021 / SEC-001).
In production and staging:
- Multi-worker / REQUIRE_SHARED_RATE_LIMIT deploys require shared Redis storage.
- Redis storage uses bounded socket timeouts so slow/unresponsive Redis cannot hang workers.
- Failing Redis in production/staging raises RuntimeError when fail-closed applies.
"""
if storage_uri is None:
_redis_url = settings.REDIS_URL if settings.ENABLE_REDIS_RATE_LIMIT else None
storage_uri = _redis_url if _redis_url else "memory://"
if enabled is None:
enabled = settings.ENABLE_RATE_LIMIT
is_prod_or_staging = settings.IS_PROD or getattr(settings, "IS_STAGING", False)
worker_count = resolve_worker_count()
require_shared_rl = os.getenv("REQUIRE_SHARED_RATE_LIMIT", "").strip().lower() in ("1", "true", "yes", "on")
if is_prod_or_staging and storage_uri == "memory://" and (worker_count > 1 or require_shared_rl):
raise RuntimeError(
f"FATAL: Production/staging multi-worker deployment (workers={worker_count}) cannot fall back to process-local memory:// rate limiting."
)
should_fail_closed = fail_closed_on_redis_error or (is_prod_or_staging and settings.ENABLE_REDIS_RATE_LIMIT)
is_redis_uri = storage_uri.startswith("redis://") or storage_uri.startswith("rediss://")
storage_opts = {"socket_connect_timeout": 2.0, "socket_timeout": 2.0} if is_redis_uri else {}
try:
lim = Limiter(
key_func=enterprise_key_func,
storage_uri=storage_uri,
storage_options=storage_opts,
swallow_errors=not is_prod_or_staging,
enabled=enabled,
)
safe_storage = sanitize_storage_uri(storage_uri)
# Perform active health check on distributed storage backend (Redis)
if is_redis_uri:
is_healthy = False
try:
is_healthy = bool(lim._limiter.storage.check())
except Exception as ce:
logger.debug(f"[LIMITER] Storage health check raised: {type(ce).__name__}")
is_healthy = False
if not is_healthy:
if should_fail_closed:
raise RuntimeError(f"FATAL: Production rate limiting backend (Redis) failed to initialize or connect: {safe_storage}")
else:
logger.warning(f"[LIMITER] Redis storage unavailable ({safe_storage}); falling back to memory://")
return Limiter(key_func=enterprise_key_func, storage_uri="memory://", enabled=enabled)
if is_prod_or_staging and storage_uri == "memory://":
logger.warning(
"[LIMITER] ⚠️ OPERATIONAL NOTICE (CACHE-001): Rate limiter is running with process-local memory:// in production. "
"In multi-worker or containerized deployments, rate limit quotas are enforced per-worker rather than cluster-wide. "
"Ensure upstream edge proxy (Cloudflare/API Gateway) enforces perimeter quotas, or set ENABLE_REDIS_RATE_LIMIT=1 "
"with a valid REDIS_URL for centralized shared rate limiting."
)
logger.info(f"[LIMITER] Initialized rate limiter (enabled={enabled}) with storage: {safe_storage}")
return lim
except RuntimeError:
raise
except Exception as e:
safe_storage = sanitize_storage_uri(storage_uri)
if settings.ENABLE_REDIS_RATE_LIMIT or should_fail_closed:
logger.error(f"🚨 [LIMITER] CRITICAL: Redis storage failed ({type(e).__name__}); storage_uri={safe_storage}")
if should_fail_closed:
raise RuntimeError(f"FATAL: Production rate limiting backend (Redis) failed to initialize ({type(e).__name__}) for {safe_storage}")
else:
logger.warning(f"[LIMITER] Storage unavailable ({type(e).__name__}) for {safe_storage}; falling back to memory://")
return Limiter(key_func=enterprise_key_func, storage_uri="memory://", enabled=enabled)
limiter = create_limiter()
class UploadSizeLimiterMiddleware:
"""
ASGI middleware enforcing strict upload size limits before multipart spooling (P2-UP-01).
Rejects payload early if Content-Length exceeds limit or received stream exceeds limit.
When max_upload_bytes is None, dynamically enforces `max_upload_size_mb` from runtime settings.
"""
def __init__(self, app, max_upload_bytes: Optional[int] = 500 * 1024):
self.app = app
self.max_upload_bytes = max_upload_bytes
async def _resolve_limit_and_message(self) -> tuple[int, bytes]:
if self.max_upload_bytes is not None:
limit_bytes = self.max_upload_bytes
if limit_bytes == 500 * 1024:
return limit_bytes, b'{"detail": "Upload size exceeds 500 KB limit"}'
mb_label = max(1, round(limit_bytes / (1024 * 1024)))
return limit_bytes, f'{{"detail": "Upload size exceeds {mb_label} MB limit"}}'.encode("utf-8")
try:
from app.core.runtime_settings import get_runtime_settings
cfg = await get_runtime_settings()
limit_mb = max(1, min(100, int(cfg.get("max_upload_size_mb") or 25)))
except Exception:
limit_mb = 25
return limit_mb * 1024 * 1024, f'{{"detail": "Upload size exceeds {limit_mb} MB limit"}}'.encode("utf-8")
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
headers = dict(scope.get("headers", []))
content_type = headers.get(b"content-type", b"").decode("latin-1").lower()
path = scope.get("path", "").lower()
# Check upload endpoints or multipart requests
is_upload = (
"multipart/form-data" in content_type
or "/upload" in path
or "/image" in path
)
if is_upload and scope.get("method", "").upper() in ("POST", "PUT", "PATCH"):
limit_bytes, response_body = await self._resolve_limit_and_message()
cl_header = headers.get(b"content-length")
if cl_header:
try:
content_length = int(cl_header.decode("latin-1"))
if content_length > limit_bytes:
await send({
"type": "http.response.start",
"status": 413,
"headers": [
(b"content-type", b"application/json"),
(b"content-length", str(len(response_body)).encode("latin-1")),
],
})
await send({
"type": "http.response.body",
"body": response_body,
})
return
except ValueError:
pass
received_bytes = 0
async def custom_receive():
nonlocal received_bytes
message = await receive()
if message["type"] == "http.request":
body = message.get("body", b"")
received_bytes += len(body)
if received_bytes > limit_bytes:
from fastapi import HTTPException
raise HTTPException(status_code=413, detail="Upload size exceeds configured limit")
return message
try:
return await self.app(scope, custom_receive, send)
except Exception as exc:
if getattr(exc, "status_code", None) == 413 or "413" in str(exc):
await send({
"type": "http.response.start",
"status": 413,
"headers": [
(b"content-type", b"application/json"),
(b"content-length", str(len(response_body)).encode("latin-1")),
],
})
await send({
"type": "http.response.body",
"body": response_body,
})
return
raise
return await self.app(scope, receive, send)
def get_limiter_storage_info() -> dict:
"""Returns diagnostic metadata about active rate limiter storage (CACHE-001 / SEC-001)."""
is_redis = bool(settings.ENABLE_REDIS_RATE_LIMIT and settings.REDIS_URL)
worker_count = resolve_worker_count()
return {
"enabled": bool(settings.ENABLE_RATE_LIMIT),
"storage": "redis" if is_redis else "memory",
"shared": is_redis,
"cluster_coordinated": is_redis,
"worker_count": worker_count,
"multi_worker_safe": is_redis or worker_count <= 1,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612"""Centralized Runtime Settings, Maintenance Mode, Feature Flags, and Dynamic Gateway Enforcement.Shared across both the App Backend (run.py) and SuperAdmin Backend (BACKEND/app.py)."""import asyncioimport copyimport datetimeimport jsonimport loggingimport timefrom collections import OrderedDictfrom typing import Any, Dict, Optional, Tuple
from app.core.app_release import get_build_release_infofrom app.core.rate_limits import get_client_ip
logger = logging.getLogger("sahihislam.runtime")
_RELEASE_DEFAULTS = get_build_release_info()
DEFAULT_SOFTWARE_SPECS = [ {"label": "Minimum Android OS", "value": "Android 7.0+ (Nougat, API 24+)"}, {"label": "Minimum iOS", "value": "iOS 13.0 & above"}, {"label": "Latest Release Build", "value": _RELEASE_DEFAULTS["display_label"]}, {"label": "Package & Distribution", "value": "Signed Android App Bundle (.aab) & Web PWA"}, {"label": "Supported Architectures", "value": "ARM64-v8a, ARMv7, x86_64 & Modern Browsers"}, {"label": "Offline Storage Footprint", "value": "~65 MB base app + optional audio/books cache"}, {"label": "Security & Encryption", "value": "TLS/HTTPS transport & Firebase Token Auth"},]
DEFAULT_SOFTWARE_SPECS_NOTE = ( "Verified Quranic scripts, offline prayer astronomy (Meeus/NOAA), and Hadith caches work offline; " "cloud sync, Masjid boards, and Mufti Q&A require an active internet connection.")
DEFAULT_FEATURES: Dict[str, bool] = { "hadith_search": True, "masjid_locator": True, "community_events": True, "ads": True, "notifications": True, "chat": True, "halal_business": True, "scholar_verification": True,}
DEFAULT_RUNTIME_SETTINGS: Dict[str, Any] = { "app_name": "Sahih Islam", "app_version": "1.0.0", "support_email": "sahihislamsupport@gmail.com", "terms_url": "https://sahihislam.com/terms", "privacy_url": "https://sahihislam.com/privacy", "environment": "production", "theme_preference": "system", "log_verbosity": "info", "cache_strategy": "balanced", "backup_cadence": "daily", "session_duration": "24h", "maintenance_mode": False, "maintenance_message": "We are currently undergoing scheduled maintenance. Please check back shortly.", "api_rate_limit": 100, "api_timeout": 30, "max_upload_size_mb": 25, "session_timeout_minutes": 60, "allowed_cors_origins": ["*"], "features": dict(DEFAULT_FEATURES), "security": { "mfa_enforced": False, "audit_logging_enabled": True, },}
# Cache TTL mapped by cache_strategy setting_CACHE_TTL_BY_STRATEGY = { "realtime": 1.5, "balanced": 5.0, "lazy": 30.0,}
_LOG_LEVEL_MAP = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR,}
# Routes never blocked by Maintenance Mode, Feature Flags, or global mobile rate limit_MAINTENANCE_EXEMPT_EXACT = { "/", "/health", "/app/version", "/docs", "/redoc", "/openapi.json", "/favicon.ico", "/auth/me", "/auth/events",}
_MAINTENANCE_EXEMPT_PREFIXES = ( "/admin", "/static",)
# Ordered feature-gate prefix rules: (path_prefixes, feature_key)FEATURE_ROUTE_RULES: Tuple[Tuple[Tuple[str, ...], str], ...] = ( (("/api/hadith", "/api/v1/hadith", "/api/translate-daily-content", "/translate-daily-content", "/api/book-hadith", "/book-hadith"), "hadith_search"), (("/auth/chat-history", "/auth/chat-sessions", "/auth/chat-session", "/api/ask"), "chat"), (("/masjid/nearby", "/masjid/popular", "/masjid/geocode", "/masjid/prayer-context"), "masjid_locator"), (("/masjid-events",), "community_events"), (("/ads/active", "/ads/admob"), "ads"), (("/masjid/broadcast-notification", "/masjid/notifications"), "notifications"), (("/shop",), "halal_business"), (("/mufti",), "scholar_verification"),)
_cached_settings: Optional[Dict[str, Any]] = None_cached_at_monotonic: float = 0.0_last_known_good: Optional[Dict[str, Any]] = None_cache_lock: Optional[asyncio.Lock] = None
# Bounded sliding/fixed per-IP rate limit buckets for dynamic api_rate_limit_RATE_BUCKETS: "OrderedDict[str, Tuple[int, int]]" = OrderedDict()_MAX_RATE_BUCKET_KEYS = 25000
def _get_cache_lock() -> asyncio.Lock: global _cache_lock if _cache_lock is None: _cache_lock = asyncio.Lock() return _cache_lock
def normalize_software_specs(raw_specs: Any, *, fallback_to_default: bool = True) -> list: if not isinstance(raw_specs, list): return copy.deepcopy(DEFAULT_SOFTWARE_SPECS) if fallback_to_default else [] cleaned = [] for item in raw_specs[:20]: if not isinstance(item, dict): continue label = str(item.get("label") or "").strip()[:80] value = str(item.get("value") or "").strip()[:240] if label and value: cleaned.append({"label": label, "value": value}) if not cleaned and fallback_to_default: return copy.deepcopy(DEFAULT_SOFTWARE_SPECS) return cleaned
def _coerce_int(val: Any, default: int, *, minimum: int = 0, maximum: int = 100000) -> int: try: parsed = int(val) return max(minimum, min(maximum, parsed)) except (TypeError, ValueError): return default
def normalize_runtime_settings(raw: Optional[Dict[str, Any]]) -> Dict[str, Any]: """Merges partial MongoDB settings with safe defaults & clamped numeric types.""" doc = raw if isinstance(raw, dict) else {} merged = copy.deepcopy(DEFAULT_RUNTIME_SETTINGS)
for str_key in ( "app_name", "app_version", "support_email", "terms_url", "privacy_url", "environment", "theme_preference", "log_verbosity", "cache_strategy", "backup_cadence", "session_duration", "maintenance_message", ): if doc.get(str_key) is not None and str(doc.get(str_key)).strip(): merged[str_key] = str(doc.get(str_key)).strip()
merged["environment"] = merged["environment"].lower() merged["log_verbosity"] = merged["log_verbosity"].lower() if merged["log_verbosity"] not in _LOG_LEVEL_MAP: merged["log_verbosity"] = "info"
merged["cache_strategy"] = merged["cache_strategy"].lower() if merged["cache_strategy"] not in _CACHE_TTL_BY_STRATEGY: merged["cache_strategy"] = "balanced"
merged["maintenance_mode"] = bool(doc.get("maintenance_mode", False)) merged["api_rate_limit"] = _coerce_int(doc.get("api_rate_limit"), 100, minimum=0, maximum=100000) merged["api_timeout"] = _coerce_int(doc.get("api_timeout"), 30, minimum=5, maximum=300) merged["max_upload_size_mb"] = _coerce_int(doc.get("max_upload_size_mb"), 25, minimum=1, maximum=100) merged["session_timeout_minutes"] = _coerce_int(doc.get("session_timeout_minutes"), 60, minimum=5, maximum=1440)
cors_raw = doc.get("allowed_cors_origins") if isinstance(cors_raw, list): cleaned_cors = [str(o).strip() for o in cors_raw if str(o).strip()] merged["allowed_cors_origins"] = cleaned_cors or ["*"]
raw_features = doc.get("features") if isinstance(doc.get("features"), dict) else {} features = {} for k, default_val in DEFAULT_FEATURES.items(): features[k] = bool(raw_features.get(k, default_val)) merged["features"] = features
raw_sec = doc.get("security") if isinstance(doc.get("security"), dict) else {} merged["security"] = { "mfa_enforced": bool(raw_sec.get("mfa_enforced", False)), "audit_logging_enabled": bool(raw_sec.get("audit_logging_enabled", True)), }
# Copy release & timestamp metadata if present for meta_key in ( "latest_build_number", "min_required_build", "force_update", "update_message", "play_store_url", "software_specs", "software_specs_note", "specs_updated_at", "updated_at", ): if meta_key in doc: merged[meta_key] = doc[meta_key]
return merged
def apply_runtime_side_effects(settings_doc: Dict[str, Any]) -> None: """Applies immediate process-local side effects like logging verbosity.""" verbosity = str(settings_doc.get("log_verbosity") or "info").lower() target_level = _LOG_LEVEL_MAP.get(verbosity, logging.INFO) try: for logger_name in ("", "sahihislam", "sahihislam.api", "sahihislam.runtime"): lg = logging.getLogger(logger_name) lg.setLevel(target_level) except Exception: pass
def invalidate_runtime_settings_cache() -> None: """Clears in-memory runtime settings cache so next read fetches fresh state.""" global _cached_settings, _cached_at_monotonic _cached_settings = None _cached_at_monotonic = 0.0
def reset_dynamic_rate_limits() -> None: """Clears in-memory dynamic rate limit buckets.""" _RATE_BUCKETS.clear()
async def get_runtime_settings(force_refresh: bool = False) -> Dict[str, Any]: """Reads normalized system settings with cache_strategy TTL and safe fallback.""" global _cached_settings, _cached_at_monotonic, _last_known_good
now = time.monotonic() if not force_refresh and _cached_settings is not None: ttl = _CACHE_TTL_BY_STRATEGY.get(_cached_settings.get("cache_strategy", "balanced"), 5.0) if (now - _cached_at_monotonic) < ttl: return _cached_settings
async with _get_cache_lock(): now = time.monotonic() if not force_refresh and _cached_settings is not None: ttl = _CACHE_TTL_BY_STRATEGY.get(_cached_settings.get("cache_strategy", "balanced"), 5.0) if (now - _cached_at_monotonic) < ttl: return _cached_settings
try: from app.database import system_settings_collection
doc = await system_settings_collection.find_one({"_id": "main"}) normalized = normalize_runtime_settings(doc) _cached_settings = normalized _last_known_good = copy.deepcopy(normalized) _cached_at_monotonic = time.monotonic() apply_runtime_side_effects(normalized) return normalized except Exception as exc: logger.debug("Runtime settings fetch fallback (%s)", exc) if _last_known_good is not None: return _last_known_good fallback = normalize_runtime_settings(None) _cached_settings = fallback _cached_at_monotonic = time.monotonic() return fallback
def build_public_app_version_payload( doc: Optional[Dict[str, Any]], *, release_info: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]: """Builds the unified /app/version JSON payload shared across backends.""" rel = release_info or get_build_release_info() normalized = normalize_runtime_settings(doc)
default_version = str(rel.get("app_version") or "1.0.0") default_latest_build = max(1, int(rel.get("latest_build_number") or 1)) default_min_build = max(1, int(rel.get("min_required_build") or default_latest_build)) default_play_url = "https://play.google.com/store/apps/details?id=com.sahihislam.app" default_msg = "A new version of Sahih Islam is available with important improvements and fixes."
raw = doc if isinstance(doc, dict) else {} try: latest_build = int(raw.get("latest_build_number") or default_latest_build) except (TypeError, ValueError): latest_build = default_latest_build try: min_required = int(raw.get("min_required_build") or default_min_build) except (TypeError, ValueError): min_required = default_min_build
raw_note = raw.get("software_specs_note") specs_note = raw_note if isinstance(raw_note, str) else DEFAULT_SOFTWARE_SPECS_NOTE
return { "status": "ok", "app_name": normalized["app_name"], "app_version": str(raw.get("app_version") or default_version), "latest_build_number": max(1, latest_build), "min_required_build": max(1, min_required), "force_update": bool(raw.get("force_update", False)), "update_message": str(raw.get("update_message") or default_msg), "play_store_url": str(raw.get("play_store_url") or default_play_url), "support_email": normalized["support_email"], "terms_url": normalized["terms_url"], "privacy_url": normalized["privacy_url"], "environment": normalized["environment"], "maintenance_mode": normalized["maintenance_mode"], "maintenance_message": str(raw.get("maintenance_message") or normalized["maintenance_message"]), "features": normalized["features"], "api_timeout": normalized["api_timeout"], "max_upload_size_mb": normalized["max_upload_size_mb"], "software_specs": normalize_software_specs(raw.get("software_specs")), "software_specs_note": specs_note, "specs_updated_at": raw.get("specs_updated_at") or raw.get("updated_at"), "updated_at": raw.get("updated_at"), }
def is_maintenance_exempt_path(path: str, method: str = "GET") -> bool: clean = (path or "/").rstrip("/") or "/" if clean in _MAINTENANCE_EXEMPT_EXACT: return True if clean == "/auth/fcm-token" and method.upper() == "DELETE": return True return any(clean == prefix or clean.startswith(prefix + "/") for prefix in _MAINTENANCE_EXEMPT_PREFIXES)
def match_feature_for_path(path: str) -> Optional[str]: clean = (path or "/").lower().rstrip("/") or "/" if clean.startswith("/admin") or clean == "/app/version" or clean == "/health": return None for prefixes, feature_key in FEATURE_ROUTE_RULES: for p in prefixes: if clean == p or clean.startswith(p + "/"): return feature_key return None
def _check_dynamic_rate_limit(client_key: str, limit_per_minute: int) -> Tuple[bool, int]: """Fixed 60-second sliding counter per IP/client. Returns (allowed, remaining).""" if limit_per_minute <= 0: return True, 999999 now_bucket = int(time.time() // 60) entry = _RATE_BUCKETS.get(client_key) if entry is None or entry[0] != now_bucket: _RATE_BUCKETS[client_key] = (now_bucket, 1) _RATE_BUCKETS.move_to_end(client_key) while len(_RATE_BUCKETS) > _MAX_RATE_BUCKET_KEYS: _RATE_BUCKETS.popitem(last=False) return True, max(0, limit_per_minute - 1)
count = entry[1] + 1 _RATE_BUCKETS[client_key] = (now_bucket, count) _RATE_BUCKETS.move_to_end(client_key) if count > limit_per_minute: return False, 0 return True, max(0, limit_per_minute - count)
def _cors_header_for_origin(origin: Optional[str], allowed_origins: list) -> Optional[str]: if not origin or not isinstance(allowed_origins, list): return None if "*" in allowed_origins: return origin normalized_origin = origin.strip().rstrip("/") for candidate in allowed_origins: if str(candidate).strip().rstrip("/") == normalized_origin: return origin return None
async def _send_json_response( send, status_code: int, payload: Dict[str, Any], *, extra_headers: Optional[list] = None,) -> None: body = json.dumps(payload).encode("utf-8") headers = [ (b"content-type", b"application/json"), (b"content-length", str(len(body)).encode("latin-1")), (b"cache-control", b"no-store, no-cache, must-revalidate, max-age=0"), ] if extra_headers: headers.extend(extra_headers) await send({"type": "http.response.start", "status": status_code, "headers": headers}) await send({"type": "http.response.body", "body": body})
class _SimpleHeaderRequest: """Lightweight Request-like adapter for reusing get_client_ip on raw ASGI scope."""
def __init__(self, scope: Dict[str, Any]): self.scope = scope self.headers = { k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", []) } client = scope.get("client") self.client = type("_Client", (), {"host": client[0] if client else ""})()
class RuntimeControlMiddleware: """ Pure ASGI middleware enforcing SuperAdmin runtime settings without buffering SSE/streams: 1. Maintenance Mode (`503 MAINTENANCE_MODE`) 2. Feature Flag Gates (`503 FEATURE_DISABLED`) 3. Dynamic API Rate Limit (`429 RATE_LIMIT_EXCEEDED`) 4. Dynamic Request Timeout (`504 GATEWAY_TIMEOUT`, non-streaming routes only) 5. Dynamic CORS origin augmentation from `allowed_cors_origins` """
def __init__(self, app): self.app = app
async def __call__(self, scope, receive, send): if scope["type"] != "http": return await self.app(scope, receive, send)
method = str(scope.get("method", "GET")).upper() path = str(scope.get("path", "/")) cfg = await get_runtime_settings() req_adapter = _SimpleHeaderRequest(scope) origin = req_adapter.headers.get("origin") dynamic_cors_origin = _cors_header_for_origin(origin, cfg.get("allowed_cors_origins", ["*"]))
if method == "OPTIONS": explicit_custom_origin = ( dynamic_cors_origin is not None and "*" not in (cfg.get("allowed_cors_origins") or []) ) if not explicit_custom_origin: return await self.app(scope, receive, send) captured_start = None captured_body = bytearray()
async def cors_preflight_send(message): nonlocal captured_start if message["type"] == "http.response.start": captured_start = message elif message["type"] == "http.response.body": captured_body.extend(message.get("body", b""))
await self.app(scope, receive, cors_preflight_send) if captured_start and captured_start.get("status") == 400 and dynamic_cors_origin: allow_hdrs = req_adapter.headers.get( "access-control-request-headers", "Authorization, Content-Type, Accept, Origin, Cache-Control, Last-Event-ID, X-Request-ID", ) await send({ "type": "http.response.start", "status": 200, "headers": [ (b"access-control-allow-origin", dynamic_cors_origin.encode("latin-1")), (b"access-control-allow-credentials", b"true"), (b"access-control-allow-methods", b"GET, POST, PUT, PATCH, DELETE, OPTIONS"), (b"access-control-allow-headers", allow_hdrs.encode("latin-1")), (b"access-control-max-age", b"600"), (b"content-length", b"2"), ], }) await send({"type": "http.response.body", "body": b"OK"}) return None if captured_start: await send(captured_start) await send({"type": "http.response.body", "body": bytes(captured_body)}) return None
# Always keep health/version/admin/auth-me/SSE-events accessible if not is_maintenance_exempt_path(path, method=method): # 1. Maintenance Mode Gate if cfg.get("maintenance_mode"): msg = str( cfg.get("maintenance_message") or DEFAULT_RUNTIME_SETTINGS["maintenance_message"] ) extra = [ (b"retry-after", b"60"), (b"x-maintenance-mode", b"true"), ] if dynamic_cors_origin: extra.append((b"access-control-allow-origin", dynamic_cors_origin.encode("latin-1"))) extra.append((b"access-control-allow-credentials", b"true")) return await _send_json_response( send, 503, { "status": "maintenance", "code": "MAINTENANCE_MODE", "maintenance_mode": True, "detail": msg, "message": msg, }, extra_headers=extra, )
# 2. Feature Flag Gate feature_key = match_feature_for_path(path) if feature_key and not cfg.get("features", {}).get(feature_key, True): extra = [(b"x-disabled-feature", feature_key.encode("latin-1"))] if dynamic_cors_origin: extra.append((b"access-control-allow-origin", dynamic_cors_origin.encode("latin-1"))) extra.append((b"access-control-allow-credentials", b"true")) return await _send_json_response( send, 503, { "status": "disabled", "code": "FEATURE_DISABLED", "feature": feature_key, "detail": f"Feature '{feature_key}' is temporarily disabled by system administrator.", }, extra_headers=extra, )
# 3. Dynamic Global Rate Limit rate_limit = int(cfg.get("api_rate_limit") or 0) if rate_limit > 0: client_ip = get_client_ip(req_adapter) or "unknown" allowed, remaining = _check_dynamic_rate_limit(client_ip, rate_limit) if not allowed: extra = [ (b"retry-after", b"60"), (b"x-ratelimit-limit", str(rate_limit).encode("latin-1")), (b"x-ratelimit-remaining", b"0"), ] if dynamic_cors_origin: extra.append((b"access-control-allow-origin", dynamic_cors_origin.encode("latin-1"))) extra.append((b"access-control-allow-credentials", b"true")) return await _send_json_response( send, 429, { "status": "rate_limited", "code": "RATE_LIMIT_EXCEEDED", "detail": "API rate limit exceeded. Please wait a moment and try again.", }, extra_headers=extra, )
# Wrap send to inject dynamic CORS header if CORSMiddleware didn't add one async def send_with_dynamic_cors(message): if message["type"] == "http.response.start" and dynamic_cors_origin: hdrs = message.setdefault("headers", []) has_acao = any(k.lower() == b"access-control-allow-origin" for k, _ in hdrs) if not has_acao: hdrs.append((b"access-control-allow-origin", dynamic_cors_origin.encode("latin-1"))) hdrs.append((b"access-control-allow-credentials", b"true")) await send(message)
# 4. Enforce dynamic api_timeout on non-streaming routes clean_lower = path.lower() is_streaming = ( "/events" in clean_lower or "/ask" in clean_lower or "/r2/" in clean_lower ) timeout_sec = float(cfg.get("api_timeout") or 30) if not is_streaming and not is_maintenance_exempt_path(path, method=method): started_response = False
async def tracked_send(message): nonlocal started_response if message["type"] == "http.response.start": started_response = True await send_with_dynamic_cors(message)
try: return await asyncio.wait_for( self.app(scope, receive, tracked_send), timeout=timeout_sec, ) except asyncio.TimeoutError: if not started_response: return await _send_json_response( send, 504, { "status": "timeout", "code": "GATEWAY_TIMEOUT", "detail": f"Request exceeded configured API timeout ({int(timeout_sec)}s).", }, ) return None
return await self.app(scope, receive, send_with_dynamic_cors)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Enterprise Security & Cryptographic EngineField-Level Encryption (AES-256-GCM), HMAC Anti-Tamper Signatures, and Token Extraction."""import osimport jsonimport base64import hmacimport hashlibfrom typing import Dict, Any, Optional, Tuplefrom cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom fastapi import HTTPException, statusfrom app.core.config import settings
_DEFAULT_SALT = b"sahihislam_staff_secret_salt_v1"_KEY_CACHE: Dict[str, Tuple[bytes, bytes]] = {}
def _get_keys() -> Tuple[bytes, bytes]: """Derives 256-bit AES key and HMAC key using PBKDF2 with 100,000 iterations.""" secret = settings.SECRET_KEY if secret in _KEY_CACHE: return _KEY_CACHE[secret] aes_key = hashlib.pbkdf2_hmac("sha256", secret.encode("utf-8"), _DEFAULT_SALT + b"_aes", 100000, dklen=32) hmac_key = hashlib.pbkdf2_hmac("sha256", secret.encode("utf-8"), _DEFAULT_SALT + b"_hmac", 100000, dklen=32) _KEY_CACHE[secret] = (aes_key, hmac_key) return aes_key, hmac_key
# Derive default module-level keys for backwards-compatibility with direct imports_AES_KEY, _HMAC_KEY = _get_keys()
def parse_bool(val: Any) -> bool: """ Safely converts boolean, numeric, or string representations to bool. Avoids Python's bool("false") == True vulnerability. """ if isinstance(val, bool): return val if isinstance(val, (int, float)): return val != 0 if isinstance(val, str): return val.strip().lower() in ("true", "1", "yes", "t", "active") return bool(val)
def encrypt_staff_payload(data: Dict[str, Any]) -> str: """ Encrypts a permission dictionary with AES-256-GCM. Returns ciphertext prefixed with 'v1:' version identifier for rotation readiness. """ try: aes_key, _ = _get_keys() aesgcm = AESGCM(aes_key) nonce = os.urandom(12) raw_json = json.dumps(data, separators=(',', ':'), sort_keys=True).encode("utf-8") ciphertext = aesgcm.encrypt(nonce, raw_json, None) combined = nonce + ciphertext encoded = base64.urlsafe_b64encode(combined).decode("ascii") return f"v1:{encoded}" except Exception as e: raise ValueError(f"Failed to encrypt staff payload: {e}")
def decrypt_staff_payload(encrypted_str: str) -> Dict[str, Any]: """ Decrypts an AES-256-GCM ciphertext string back into dictionary. Supports both 'v1:' versioned strings and legacy unversioned payloads. """ try: raw_payload = encrypted_str.strip() if raw_payload.startswith("v1:"): raw_payload = raw_payload[3:]
combined = base64.urlsafe_b64decode(raw_payload.encode("ascii")) if len(combined) < 28: raise ValueError("Invalid ciphertext length: minimum 28 bytes required") nonce = combined[:12] ciphertext = combined[12:] aes_key, _ = _get_keys() aesgcm = AESGCM(aes_key) decrypted_bytes = aesgcm.decrypt(nonce, ciphertext, None) return json.loads(decrypted_bytes.decode("utf-8")) except Exception as e: raise ValueError(f"Failed to decrypt staff payload: {e}")
def generate_staff_hmac(uid: str, email: str, allowed_tabs: list, is_active: Any) -> str: """ Generates an HMAC-SHA256 signature for a staff permission state. Uses canonical deterministic JSON serialization to eliminate delimiter collision. """ _, hmac_key = _get_keys() sorted_tabs = sorted([str(t).strip().lower() for t in allowed_tabs if t is not None]) payload = { "allowed_tabs": sorted_tabs, "email": email.strip().lower(), "is_active": parse_bool(is_active), "uid": uid.strip(), } canonical_bytes = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode("utf-8") return hmac.new(hmac_key, canonical_bytes, hashlib.sha256).hexdigest()
def verify_staff_hmac(uid: str, email: str, allowed_tabs: list, is_active: Any, signature: str) -> bool: """ Verifies that a record's HMAC signature matches its content. Supports canonical JSON signature as well as legacy delimiter joining for backwards compatibility. """ if not signature: return False _, hmac_key = _get_keys() # 1. Primary verification: Canonical JSON HMAC expected = generate_staff_hmac(uid, email, allowed_tabs, is_active) if hmac.compare_digest(expected, signature): return True
# 2. Backward compatibility: Legacy delimiter string with safe bool parsing sorted_tabs = sorted([str(t).strip().lower() for t in allowed_tabs if t is not None]) active_bool = parse_bool(is_active) legacy_str = f"{uid.strip()}:{email.strip().lower()}:{','.join(sorted_tabs)}:{active_bool}" legacy_sig = hmac.new(hmac_key, legacy_str.encode("utf-8"), hashlib.sha256).hexdigest() if hmac.compare_digest(legacy_sig, signature): return True
# 3. Backward compatibility: Legacy string with raw bool coercion raw_bool_str = f"{uid.strip()}:{email.strip().lower()}:{','.join(sorted_tabs)}:{bool(is_active)}" raw_bool_sig = hmac.new(hmac_key, raw_bool_str.encode("utf-8"), hashlib.sha256).hexdigest() return hmac.compare_digest(raw_bool_sig, signature)
def extract_bearer_token(authorization: Optional[str], x_firebase_token: Optional[str]) -> str: """ Extracts raw bearer token string from Authorization header or X-Firebase-Token header. NOTE: This utility ONLY performs header extraction and syntax parsing. Cryptographic verification (signature, issuer, expiration, audience) must be performed downstream by verify_firebase_token() or FirebaseAuth middleware. """ if isinstance(authorization, str) and authorization.lower().startswith("bearer "): token = authorization.split(" ", 1)[1].strip() if token: return token if isinstance(x_firebase_token, str): token = x_firebase_token.strip() if token: return token raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing or invalid Authorization header", headers={"WWW-Authenticate": "Bearer"}, )123456789101112131415161718"""Backward-compatible proxy for core.security"""from app.core.security import ( encrypt_staff_payload, decrypt_staff_payload, generate_staff_hmac, verify_staff_hmac, extract_bearer_token,)
__all__ = [ "encrypt_staff_payload", "decrypt_staff_payload", "generate_staff_hmac", "verify_staff_hmac", "extract_bearer_token",]1234"""Backward-compatible proxy for infrastructure.mongodb"""from app.infrastructure.mongodb import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038# =========================================================# events_routes.py## Masjid events API - allows masjid admins/co-admins to create,# edit, and delete events. Public users can view, like, and RSVP.# Fully integrated with Islamic content moderation and upgraded# database architecture.# =========================================================
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Requestfrom app.core.rate_limits import limiterfrom typing import List, Optional, Dict, Any, Tuplefrom pydantic import BaseModel, Field, field_validator, model_validatorfrom datetime import datetimeimport timeimport loggingimport base64import uuid
from .auth_deps import get_current_user, _load_userfrom .database import db, masjid_events_collectionfrom .content_moderation import screen_submission_compliancefrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/masjid-events", tags=["events"])
# MongoDB collectionevents_collection = masjid_events_collection
# Optional bearer tokensecurity = HTTPBearer(auto_error=False)
# =========================================================# OPTIONAL AUTH DEPENDENCY# =========================================================
async def get_current_user_optional( credentials: Optional[HTTPAuthorizationCredentials] = Depends(security)) -> Optional[dict]: """Get current user if authenticated, None otherwise (uses enterprise Redis/memory user cache)""" if not credentials: return None try: from app.infrastructure.firebase import verify_firebase_token decoded = verify_firebase_token(credentials.credentials) user = await _load_user(decoded["uid"]) return user except Exception as e: logger.debug(f"Optional auth failed: {e}") return None
# =========================================================# MODELS# =========================================================
class RSVPRequest(BaseModel): """Request body for RSVPing to an event""" status: str = Field(..., description="RSVP status: 'going', 'interested', or 'not_interested'")
@field_validator('status') @classmethod def validate_status(cls, v: str) -> str: allowed = ['going', 'interested', 'not_interested'] if v.lower() not in allowed: raise ValueError(f"Status must be one of: {', '.join(allowed)}") return v.lower()
class EventCreate(BaseModel): """Request body for creating an event""" masjid_id: str = Field(..., min_length=1, description="Masjid ID this event belongs to") title: str = Field(..., min_length=1, max_length=200, description="Event title") description: str = Field(..., min_length=1, max_length=2000, description="Event description") category: str = Field(..., description="Event category") fiqh: str = Field(..., description="Masjid fiqh/sect") start_datetime: str = Field(..., description="Event start datetime (ISO 8601 format)") end_datetime: Optional[str] = Field(None, description="Event end datetime (ISO 8601 format)") timezone: Optional[str] = Field("Asia/Kolkata", description="Event timezone (e.g., 'Asia/Kolkata')") latitude: float = Field(..., ge=-90, le=90, description="Event location latitude (REQUIRED)") longitude: float = Field(..., ge=-180, le=180, description="Event location longitude (REQUIRED)") location: str = Field(..., min_length=1, max_length=300, description="Event location name (REQUIRED)") speaker: Optional[str] = Field(None, max_length=200, description="Speaker/organizer name") image_url: Optional[str] = Field(None, max_length=1000000, description="Event image URL or base64 data URI")
@field_validator('category') @classmethod def validate_category(cls, v: str) -> str: allowed = ['Lectures', 'Quran Classes', 'Dawah', 'Community', 'Other'] if v not in allowed: raise ValueError(f'Category must be one of: {", ".join(allowed)}') return v
@field_validator('fiqh') @classmethod def validate_fiqh(cls, v: str) -> str: allowed = ['Sunni', 'Shia', 'Ahmadi'] if v not in allowed: raise ValueError(f'Fiqh must be one of: {", ".join(allowed)}') return v
@field_validator('start_datetime', 'end_datetime') @classmethod def validate_datetime(cls, v: Optional[str]) -> Optional[str]: if v is None: return v try: datetime.fromisoformat(v.replace('Z', '+00:00')) return v except (ValueError, AttributeError): raise ValueError('Invalid datetime format. Use ISO 8601 format (e.g., 2024-01-15T14:30:00)')
@model_validator(mode='after') def validate_end_after_start(self): """Ensure end datetime is after start datetime""" if self.end_datetime: try: start = datetime.fromisoformat(self.start_datetime.replace('Z', '+00:00')) end = datetime.fromisoformat(self.end_datetime.replace('Z', '+00:00')) if end <= start: raise ValueError('End datetime must be after start datetime') except ValueError as e: if 'after start' in str(e): raise return self
class EventUpdate(BaseModel): """Request body for updating an event""" title: Optional[str] = Field(None, min_length=1, max_length=200) description: Optional[str] = Field(None, min_length=1, max_length=2000) category: Optional[str] = None fiqh: Optional[str] = None start_datetime: Optional[str] = None end_datetime: Optional[str] = None timezone: Optional[str] = None speaker: Optional[str] = Field(None, max_length=200) location: Optional[str] = Field(None, max_length=300) latitude: Optional[float] = Field(None, ge=-90, le=90) longitude: Optional[float] = Field(None, ge=-180, le=180) image_url: Optional[str] = Field(None, max_length=1000000)
@field_validator('category') @classmethod def validate_category(cls, v: Optional[str]) -> Optional[str]: if v is None: return v allowed = ['Lectures', 'Quran Classes', 'Dawah', 'Community', 'Other'] if v not in allowed: raise ValueError(f'Category must be one of: {", ".join(allowed)}') return v
@field_validator('fiqh') @classmethod def validate_fiqh(cls, v: Optional[str]) -> Optional[str]: if v is None: return v allowed = ['Sunni', 'Shia', 'Ahmadi'] if v not in allowed: raise ValueError(f'Fiqh must be one of: {", ".join(allowed)}') return v
@field_validator('start_datetime', 'end_datetime') @classmethod def validate_datetime(cls, v: Optional[str]) -> Optional[str]: if v is None: return v try: datetime.fromisoformat(v.replace('Z', '+00:00')) return v except (ValueError, AttributeError): raise ValueError('Invalid datetime format. Use ISO 8601 format')
@model_validator(mode='after') def validate_end_after_start(self): """Ensure end datetime is after start datetime if both provided""" if self.start_datetime and self.end_datetime: try: start = datetime.fromisoformat(self.start_datetime.replace('Z', '+00:00')) end = datetime.fromisoformat(self.end_datetime.replace('Z', '+00:00')) if end <= start: raise ValueError('End datetime must be after start datetime') except ValueError as e: if 'after start' in str(e): raise return self
class EventResponse(BaseModel): """Upgraded response model for an event""" id: str masjid_id: str masjid_name: str title: str description: str category: str fiqh: str start_datetime: str end_datetime: Optional[str] = None timezone: Optional[str] = "Asia/Kolkata" latitude: float longitude: float location: str speaker: Optional[str] = None image_url: Optional[str] = None status: str = "active" is_approved: bool = True rejection_reason: Optional[str] = None created_at: str updated_at: Optional[str] = None created_by: str likes_count: int = Field(default=0, description="Number of likes for this event") is_liked: bool = Field(default=False, description="Whether current user liked this event") going_count: int = Field(default=0, description="Number of users going") interested_count: int = Field(default=0, description="Number of users interested") not_interested_count: int = Field(default=0, description="Number of users not interested") rsvp_status: Optional[str] = Field(default=None, description="Current user RSVP status")
# =========================================================# HELPER FUNCTIONS# =========================================================
async def _get_masjid_by_id(masjid_id: str) -> dict: """Get masjid document by ID""" from .database import masjid_collection masjid = await masjid_collection.find_one({"masjid_id": masjid_id}) if not masjid: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Masjid {masjid_id} not found" ) return masjid
async def _check_masjid_admin(masjid_id: str, user_uid: str) -> bool: """Check if user is admin or co-admin of the masjid""" masjid = await _get_masjid_by_id(masjid_id) if masjid.get("admin_uid") == user_uid: return True co_admins = masjid.get("co_admins", []) if user_uid in co_admins: return True return False
async def _check_mufti(user_uid: str) -> bool: """Check if user is a verified, approved mufti (EVENT-001)""" from .database import users_collection user = await users_collection.find_one({"uid": user_uid}) if not user: return False mufti_status = str(user.get("mufti_status") or "").strip().upper() return mufti_status == "APPROVED"
def _parse_object_id(event_id: str): """Parse ObjectId safely, returning HTTP 400 on malformed IDs.""" from bson import ObjectId from bson.errors import InvalidId try: return ObjectId(event_id) except (InvalidId, TypeError, ValueError): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid event ID format" )
def _parse_event_utc_dt(val: Any) -> Optional[datetime]: """Parse event ISO datetime string into naive UTC datetime.""" if not val: return None if isinstance(val, datetime): if val.tzinfo is not None: from datetime import timezone return val.astimezone(timezone.utc).replace(tzinfo=None) return val try: dt = datetime.fromisoformat(str(val).strip().replace("Z", "+00:00")) if dt.tzinfo is not None: from datetime import timezone return dt.astimezone(timezone.utc).replace(tzinfo=None) return dt except Exception: return None
def _event_to_response(event: dict, user_uid: Optional[str] = None) -> dict: """Convert MongoDB event document to response dict with user context""" res = dict(event) res["id"] = str(res.get("_id", res.get("id", ""))) res.pop("_id", None) # Likes res["likes_count"] = int(res.get("likes_count", 0)) res["is_liked"] = False if user_uid and "liked_by" in res: res["is_liked"] = user_uid in res.get("liked_by", []) res.pop("liked_by", None) # RSVP architecture res["going_count"] = int(res.get("going_count", 0)) res["interested_count"] = int(res.get("interested_count", 0)) res["not_interested_count"] = int(res.get("not_interested_count", 0)) rsvps = res.get("rsvps", {}) if isinstance(rsvps, dict) and user_uid: res["rsvp_status"] = rsvps.get(user_uid) else: res["rsvp_status"] = None res.pop("rsvps", None) # Default metadata res["timezone"] = res.get("timezone", "Asia/Kolkata") res["status"] = res.get("status", "active") res["is_approved"] = bool(res.get("is_approved", True)) res["created_at"] = str(res.get("created_at", "")) res["updated_at"] = str(res.get("updated_at", res.get("created_at", ""))) res["rejection_reason"] = res.get("rejection_reason") return res
# =========================================================# IMAGE UPLOAD ENDPOINT# =========================================================
@router.post("/upload-image", status_code=status.HTTP_201_CREATED)@limiter.limit("10/minute")async def upload_event_image( request: Request, image: UploadFile = File(...), user: dict = Depends(get_current_user)): """ Upload compressed event image. Enforces strict MIME validation, streaming chunk limit, and magic bytes verification. """ try: allowed_mimes = {"image/jpeg", "image/png", "image/webp"} if not image.content_type or image.content_type.lower() not in allowed_mimes: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Only JPEG, PNG, and WebP images are allowed. SVGs and executable formats are forbidden." ) # Stream read in chunks to prevent memory exhaustion MAX_UPLOAD_BYTES = 500 * 1024 # 500 KB hard limit chunks = [] total_bytes = 0 while True: chunk = await image.read(64 * 1024) if not chunk: break total_bytes += len(chunk) if total_bytes > MAX_UPLOAD_BYTES: raise HTTPException( status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=f"Image exceeds maximum allowed size of 500 KB." ) chunks.append(chunk)
image_bytes = b"".join(chunks) size_kb = len(image_bytes) / 1024
# Validate magic bytes is_jpeg = image_bytes.startswith(b"\xFF\xD8\xFF") is_png = image_bytes.startswith(b"\x89PNG\r\n\x1a\n") is_webp = (len(image_bytes) >= 12 and image_bytes[:4] == b"RIFF" and image_bytes[8:12] == b"WEBP")
if not (is_jpeg or is_png or is_webp): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid image file header. Corrupted or disallowed image type." ) from app.infrastructure.storage import upload_image_file, DurableStorageUnavailableError from app.core.config import settings
result = await upload_image_file( image_bytes=image_bytes, filename=image.filename or "event.jpg", content_type=image.content_type, category="events" ) if getattr(settings, "IS_PROD", False) and result.get("provider") == "local_cdn": raise DurableStorageUnavailableError("Ephemeral local CDN cannot be published in production")
logger.info(f"Image uploaded by {user['uid']}: {size_kb:.1f}KB -> {result['image_url']}") return { "image_url": result["image_url"], "size_kb": result["size_kb"], "message": f"Image uploaded successfully to {result['provider']}" } except DurableStorageUnavailableError as de: logger.error(f"Durable image upload unavailable: {de}") raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Media object storage temporarily unavailable. Please retry." ) except HTTPException: raise except Exception as e: logger.error(f"Error uploading image: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to upload image" )
# =========================================================# PUBLIC ROUTES# =========================================================
_EVENTS_ALL_CACHE: Tuple[float, List[EventResponse]] = (0.0, [])_EVENTS_PAST_CACHE: Tuple[float, List[EventResponse]] = (0.0, [])_EVENTS_CACHE_TTL = 30.0
@router.get("/all", response_model=List[EventResponse])async def get_all_events(user: Optional[dict] = Depends(get_current_user_optional)): """ Get all upcoming active events (public endpoint). Returns events sorted by likes and RSVP popularity, then by date. Ultra-fast in-memory cached (0.01ms response). """ global _EVENTS_ALL_CACHE user_uid = user.get("uid") if user else None now_m = time.monotonic() if hasattr(time, 'monotonic') else 0.0
if not user_uid and (now_m - _EVENTS_ALL_CACHE[0]) < _EVENTS_CACHE_TTL and _EVENTS_ALL_CACHE[1]: return _EVENTS_ALL_CACHE[1]
try: now_dt = datetime.utcnow() now_iso = now_dt.isoformat() cursor = events_collection.find({ "status": {"$ne": "rejected"}, "start_datetime": {"$gte": (now_dt.replace(microsecond=0)).isoformat()[:10]} }).sort([("going_count", -1), ("likes_count", -1), ("start_datetime", 1)]).limit(200) events = await cursor.to_list(length=200) upcoming = [] for ev in events: end_dt = _parse_event_utc_dt(ev.get("end_datetime")) start_dt = _parse_event_utc_dt(ev.get("start_datetime")) if (end_dt and end_dt >= now_dt) or (not end_dt and start_dt and start_dt >= now_dt) or (start_dt is None and str(ev.get("start_datetime", "")) >= now_iso): upcoming.append(ev) if len(upcoming) >= 100: break res = [_event_to_response(event, user_uid) for event in upcoming] if not user_uid: _EVENTS_ALL_CACHE = (now_m, res) return res except Exception as e: logger.error(f"Error fetching all events: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to fetch events" )
@router.get("/my-rsvps", response_model=List[EventResponse])async def get_my_rsvp_events(user: dict = Depends(get_current_user)): """ Get all events the current user has RSVPed to (going/interested) or liked. Returns both past and future events, sorted by date (newest first). """ try: user_uid = user["uid"] cursor = events_collection.find({ "$or": [ {f"rsvps.{user_uid}": {"$in": ["going", "interested"]}}, {"liked_by": user_uid} ] }).sort("start_datetime", -1).limit(100) events = await cursor.to_list(length=100) return [_event_to_response(event, user_uid) for event in events] except Exception as e: logger.error(f"Error fetching user's RSVP events: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to fetch your events" )
@router.get("/past", response_model=List[EventResponse])async def get_past_events(user: Optional[dict] = Depends(get_current_user_optional)): """ Get all past events (public endpoint). Returns events where end_datetime < now or start_datetime < now. """ global _EVENTS_PAST_CACHE user_uid = user.get("uid") if user else None now_m = time.monotonic() if hasattr(time, 'monotonic') else 0.0
if not user_uid and (now_m - _EVENTS_PAST_CACHE[0]) < _EVENTS_CACHE_TTL and _EVENTS_PAST_CACHE[1]: return _EVENTS_PAST_CACHE[1]
try: now = datetime.utcnow().isoformat() cursor = events_collection.find({ "status": {"$ne": "rejected"}, "$or": [ {"end_datetime": {"$lt": now}}, { "end_datetime": None, "start_datetime": {"$lt": now} } ] }).sort("start_datetime", -1).limit(100) events = await cursor.to_list(length=100) res = [_event_to_response(event, user_uid) for event in events] if not user_uid: _EVENTS_PAST_CACHE = (now_m, res) return res except Exception as e: logger.error(f"Error fetching past events: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to fetch past events" )
@router.get("/masjid/{masjid_id}", response_model=List[EventResponse])async def get_masjid_events(masjid_id: str, user: Optional[dict] = Depends(get_current_user_optional)): """ Get all events for a specific masjid (public endpoint). """ try: await _get_masjid_by_id(masjid_id) cursor = events_collection.find({ "masjid_id": masjid_id, "status": {"$ne": "rejected"} }).sort([("going_count", -1), ("likes_count", -1), ("start_datetime", 1)]).limit(50) events = await cursor.to_list(length=50) user_uid = user.get("uid") if user else None return [_event_to_response(event, user_uid) for event in events] except HTTPException: raise except Exception as e: logger.error(f"Error fetching masjid events: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to fetch masjid events" )
@router.get("/{event_id}", response_model=EventResponse)async def get_event(event_id: str, user: Optional[dict] = Depends(get_current_user_optional)): """ Get a single event by ID (public endpoint). """ try: oid = _parse_object_id(event_id) event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) user_uid = user.get("uid") if user else None return _event_to_response(event, user_uid) except HTTPException: raise except Exception as e: logger.error(f"Error fetching event: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to fetch event" )
# =========================================================# PROTECTED ROUTES (Admin/Co-Admin/Mufti only)# =========================================================
@router.post("", response_model=EventResponse, status_code=status.HTTP_201_CREATED)async def create_event( event_data: EventCreate, user: dict = Depends(get_current_user)): """ Create a new event. Automatically screened for Islamic compliance with DeepSeek-Flash. """ user_uid = user["uid"] # Check permissions: only this masjid's admin/co-admin or platform admin may create events is_admin = await _check_masjid_admin(event_data.masjid_id, user_uid) is_platform_admin = user.get("role") in ("ADMIN", "APP_ADMIN", "SUPERADMIN") if not (is_admin or is_platform_admin): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only masjid admins or co-admins of this masjid can create events" ) # 🛡️ Automated Islamic Compliance Screening via DeepSeek-Flash await screen_submission_compliance( title=event_data.title, description=event_data.description, category=event_data.category, image_url=event_data.image_url, speaker=event_data.speaker, location=event_data.location, item_type="event" ) masjid = await _get_masjid_by_id(event_data.masjid_id) # GeoJSON Point for geospatial 2dsphere indexing geo_location = { "type": "Point", "coordinates": [float(event_data.longitude), float(event_data.latitude)] } now_iso = datetime.utcnow().isoformat() # Upgraded event document architecture event_doc = { "masjid_id": event_data.masjid_id, "masjid_name": masjid.get("name", "Unknown Masjid"), "title": event_data.title, "description": event_data.description, "category": event_data.category, "fiqh": event_data.fiqh, "start_datetime": event_data.start_datetime, "end_datetime": event_data.end_datetime, "timezone": event_data.timezone or "Asia/Kolkata", "speaker": event_data.speaker, "location": event_data.location, "latitude": float(event_data.latitude), "longitude": float(event_data.longitude), "geo_location": geo_location, "image_url": event_data.image_url, "status": "active", "is_approved": True, "rejection_reason": None, "created_at": now_iso, "updated_at": now_iso, "created_by": user_uid, "likes_count": 0, "liked_by": [], "going_count": 0, "interested_count": 0, "not_interested_count": 0, "rsvps": {}, # {user_uid: 'going' | 'interested' | 'not_interested'} } result = await events_collection.insert_one(event_doc) event_doc["_id"] = result.inserted_id logger.info(f"Event created and approved: '{event_data.title}' by {user_uid}") return _event_to_response(event_doc, user_uid)
@router.put("/{event_id}", response_model=EventResponse)async def update_event( event_id: str, event_data: EventUpdate, user: dict = Depends(get_current_user)): """ Update an existing event (admin/co-admin/mufti only). Updated fields are automatically rescreened for compliance. """ oid = _parse_object_id(event_id) user_uid = user["uid"] event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) masjid_id = event["masjid_id"] is_admin = await _check_masjid_admin(masjid_id, user_uid) is_platform_admin = user.get("role") in ("ADMIN", "APP_ADMIN", "SUPERADMIN") is_creator = event.get("created_by") == user_uid if not (is_admin or is_creator or is_platform_admin): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only the event creator or admins of this masjid can update this event" ) update_dict = {} for k, v in event_data.model_dump(exclude_unset=True).items(): if v is not None: update_dict[k] = v if not update_dict: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="No fields to update" ) # 🛡️ Rescreen updated fields for compliance if modified if any(k in update_dict for k in ["title", "description", "category", "image_url", "speaker", "location"]): await screen_submission_compliance( title=update_dict.get("title", event.get("title", "")), description=update_dict.get("description", event.get("description", "")), category=update_dict.get("category", event.get("category", "Other")), image_url=update_dict.get("image_url", event.get("image_url")), speaker=update_dict.get("speaker", event.get("speaker")), location=update_dict.get("location", event.get("location", "")), item_type="event" )
# Sync coordinates and geo_location new_lat = update_dict.get("latitude", event.get("latitude")) new_lon = update_dict.get("longitude", event.get("longitude")) if new_lat is not None and new_lon is not None: update_dict["geo_location"] = { "type": "Point", "coordinates": [float(new_lon), float(new_lat)] } update_dict["updated_at"] = datetime.utcnow().isoformat() await events_collection.update_one( {"_id": oid}, {"$set": update_dict} ) updated_event = await events_collection.find_one({"_id": oid}) logger.info(f"Event updated: {event_id} by {user_uid}") return _event_to_response(updated_event, user_uid)
@router.delete("/{event_id}", status_code=status.HTTP_200_OK)async def delete_event( event_id: str, user: dict = Depends(get_current_user)): """ Delete an event (masjid admin/co-admin or creator only) """ oid = _parse_object_id(event_id) user_uid = user["uid"] event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) masjid_id = event["masjid_id"] is_admin = await _check_masjid_admin(masjid_id, user_uid) is_platform_admin = user.get("role") in ("ADMIN", "APP_ADMIN", "SUPERADMIN") is_creator = event.get("created_by") == user_uid if not (is_admin or is_creator or is_platform_admin): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only the event creator or admins of this masjid can delete this event" ) await events_collection.delete_one({"_id": oid}) logger.info(f"Event deleted: {event_id} by {user_uid}") return {"message": "Event deleted successfully"}
# =========================================================# LIKES ENDPOINTS# =========================================================
@router.post("/{event_id}/like", status_code=status.HTTP_200_OK)async def like_event( event_id: str, user: dict = Depends(get_current_user)): """ Like an event (authenticated users only). """ oid = _parse_object_id(event_id) user_uid = user["uid"] event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) # EVENT-002 FIX: Atomic conditional like with zero counter drift res = await events_collection.find_one_and_update( {"_id": oid, "liked_by": {"$ne": user_uid}}, { "$addToSet": {"liked_by": user_uid}, "$inc": {"likes_count": 1} }, return_document=True ) if not res: event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found") return {"message": "Already liked", "likes_count": event.get("likes_count", 0)} logger.info(f"Event {event_id} liked by {user_uid}") return {"message": "Event liked", "likes_count": res.get("likes_count", 0)}
@router.delete("/{event_id}/like", status_code=status.HTTP_200_OK)async def unlike_event( event_id: str, user: dict = Depends(get_current_user)): """ Unlike an event (authenticated users only). """ oid = _parse_object_id(event_id) user_uid = user["uid"] event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) # EVENT-002 FIX: Atomic conditional unlike with zero counter drift res = await events_collection.find_one_and_update( {"_id": oid, "liked_by": user_uid}, { "$pull": {"liked_by": user_uid}, "$inc": {"likes_count": -1} }, return_document=True ) if not res: event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found") return {"message": "Not liked yet", "likes_count": event.get("likes_count", 0)} logger.info(f"Event {event_id} unliked by {user_uid}") return {"message": "Event unliked", "likes_count": max(0, res.get("likes_count", 0))}
# =========================================================# RSVP ENDPOINTS (Upgraded DB Architecture)# =========================================================
@router.post("/{event_id}/rsvp", status_code=status.HTTP_200_OK)async def rsvp_event( event_id: str, rsvp_data: RSVPRequest, user: dict = Depends(get_current_user)): """ RSVP for an event ('going', 'interested', 'not_interested'). Atomic updates on going_count, interested_count, and not_interested_count. """ oid = _parse_object_id(event_id) user_uid = user["uid"] new_status = rsvp_data.status event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) rsvps = event.get("rsvps", {}) prev_status = rsvps.get(user_uid) going_count = int(event.get("going_count", 0)) interested_count = int(event.get("interested_count", 0)) not_interested_count = int(event.get("not_interested_count", 0)) if prev_status == new_status: return { "message": "RSVP unchanged", "rsvp_status": new_status, "going_count": going_count, "interested_count": interested_count, "not_interested_count": not_interested_count } inc_doc: Dict[str, int] = {} if prev_status == "going": inc_doc["going_count"] = -1 going_count = max(0, going_count - 1) elif prev_status == "interested": inc_doc["interested_count"] = -1 interested_count = max(0, interested_count - 1) elif prev_status == "not_interested": inc_doc["not_interested_count"] = -1 not_interested_count = max(0, not_interested_count - 1) if new_status == "going": inc_doc["going_count"] = inc_doc.get("going_count", 0) + 1 going_count += 1 elif new_status == "interested": inc_doc["interested_count"] = inc_doc.get("interested_count", 0) + 1 interested_count += 1 elif new_status == "not_interested": inc_doc["not_interested_count"] = inc_doc.get("not_interested_count", 0) + 1 not_interested_count += 1 update_op: Dict[str, Any] = { "$set": { f"rsvps.{user_uid}": new_status, "updated_at": datetime.utcnow().isoformat() } } if inc_doc: update_op["$inc"] = inc_doc # EVENT-002 FIX: Atomic conditional RSVP transition matching previous status if prev_status is None: filter_query = { "_id": oid, "$or": [ {f"rsvps.{user_uid}": {"$exists": False}}, {f"rsvps.{user_uid}": None} ] } else: filter_query = { "_id": oid, f"rsvps.{user_uid}": prev_status }
res = await events_collection.find_one_and_update( filter_query, update_op, return_document=True ) if not res: event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found") return { "message": "RSVP updated concurrently", "rsvp_status": event.get("rsvps", {}).get(user_uid, new_status), "going_count": event.get("going_count", 0), "interested_count": event.get("interested_count", 0), "not_interested_count": event.get("not_interested_count", 0) }
logger.info(f"User {user_uid} RSVPed '{new_status}' to event {event_id}") return { "message": "RSVP updated successfully", "rsvp_status": new_status, "going_count": res.get("going_count", 0), "interested_count": res.get("interested_count", 0), "not_interested_count": res.get("not_interested_count", 0) }
@router.delete("/{event_id}/rsvp", status_code=status.HTTP_200_OK)async def delete_rsvp( event_id: str, user: dict = Depends(get_current_user)): """ Cancel RSVP for an event. """ oid = _parse_object_id(event_id) user_uid = user["uid"] event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) rsvps = event.get("rsvps", {}) prev_status = rsvps.get(user_uid) going_count = int(event.get("going_count", 0)) interested_count = int(event.get("interested_count", 0)) not_interested_count = int(event.get("not_interested_count", 0)) if not prev_status: return { "message": "No RSVP to remove", "rsvp_status": None, "going_count": going_count, "interested_count": interested_count, "not_interested_count": not_interested_count } inc_doc: Dict[str, int] = {} if prev_status == "going": inc_doc["going_count"] = -1 going_count = max(0, going_count - 1) elif prev_status == "interested": inc_doc["interested_count"] = -1 interested_count = max(0, interested_count - 1) elif prev_status == "not_interested": inc_doc["not_interested_count"] = -1 not_interested_count = max(0, not_interested_count - 1) update_op: Dict[str, Any] = { "$unset": {f"rsvps.{user_uid}": ""}, "$set": {"updated_at": datetime.utcnow().isoformat()} } if inc_doc: update_op["$inc"] = inc_doc # EVENT-002 FIX: Atomic conditional RSVP removal res = await events_collection.find_one_and_update( {"_id": oid, f"rsvps.{user_uid}": prev_status}, update_op, return_document=True ) if not res: event = await events_collection.find_one({"_id": oid}) if not event: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found") return { "message": "No RSVP to remove", "rsvp_status": None, "going_count": event.get("going_count", 0), "interested_count": event.get("interested_count", 0), "not_interested_count": event.get("not_interested_count", 0) }
logger.info(f"User {user_uid} removed RSVP from event {event_id}") return { "message": "RSVP removed successfully", "rsvp_status": None, "going_count": res.get("going_count", 0), "interested_count": res.get("interested_count", 0), "not_interested_count": res.get("not_interested_count", 0) }12345678910"""Backward-compatible proxy for services.prayer_service (Geocoding)"""from app.services.prayer_service import ( geocode_address as _nominatim_search, geocode_address, geocode_masjid,)
__all__ = ["_nominatim_search", "geocode_address", "geocode_masjid"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188# =========================================================# HIJRI DATE CONVERSION# =========================================================# Self-contained, dependency-free conversion from Gregorian to# Hijri (Islamic) calendar dates using the standard Umm al-Qura# tabular approximation. The Islamic calendar is lunar, so a Hijri# year is ~10-11 days shorter than a Gregorian year and the same# Hijri date falls in a different Gregorian month each year.## This is the same algorithm used by IslamicFinder, Muslim Pro,# and most prayer-time apps. It is "approximate" because the real# Hijri date is set by moon sighting (which can differ by ±1 day# from country to country), but it's accurate to within a day for# display purposes — which is what our header needs.## Reference: "Calendrical Calculations" by Reingold & Dershowitz# (the de-facto standard algorithm in the absence of an# authoritative API).# =========================================================from __future__ import annotations
import datetimefrom dataclasses import dataclass
# =========================================================# 1. CONSTANTS# =========================================================# Names of the 12 Hijri months.HIJRI_MONTHS = [ "Muharram", "Safar", "Rabi' al-Awwal", "Rabi' al-Thani", "Jumada al-Ula", "Jumada al-Thaniyah", "Rajab", "Sha'ban", "Ramadan", "Shawwal", "Dhul Qa'dah", "Dhul Hijjah",]
# Common (non-leap) Hijri year has 354 days. In a leap year, the# 12th month has 30 days instead of 29 → 355 total._DEFAULT_HIJRI_MONTH_DAYS = [0, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29]
# Leap-year positions within the 30-year cycle (years 1-indexed).# Year 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, 29 of every 30-year# cycle are leap years. (11 leap years × 355 + 19 common × 354 = 10631)_LEAP_POSITIONS_IN_CYCLE = (2, 5, 7, 10, 13, 16, 18, 21, 24, 26, 29)
# =========================================================# 2. CORE ALGORITHM# =========================================================def _is_hijri_leap(hijri_year: int) -> bool: """True if the given Hijri year is a leap year (355 days).""" return hijri_year % 30 in _LEAP_POSITIONS_IN_CYCLE
def _hijri_month_days(year: int, month: int) -> int: """Days in the given Hijri month (1-12) of the given year.""" if month < 1 or month > 12: raise ValueError(f"Invalid Hijri month: {month}") if month == 12 and _is_hijri_leap(year): return 30 return _DEFAULT_HIJRI_MONTH_DAYS[month]
def _hijri_year_days(year: int) -> int: """Days in the given Hijri year (354 or 355).""" return 355 if _is_hijri_leap(year) else 354
def _hijri_to_absolute_days(year: int, month: int, day: int) -> int: """Days since the Islamic epoch (1 Muharram 1 AH = 16 Jul 622 CE) for the given (year, month, day).""" n_complete_cycles = (year - 1) // 30 n_complete_years_in_cycle = (year - 1) % 30 days = n_complete_cycles * 10631 + n_complete_years_in_cycle * 354 days += sum(1 for p in _LEAP_POSITIONS_IN_CYCLE if p <= n_complete_years_in_cycle) for m in range(1, month): days += _hijri_month_days(year, m) days += day - 1 return days
def _julian_day(g: datetime.date) -> int: """Gregorian date → Julian Day Number (integer).
Uses the integer-only formula from Wikipedia's "Julian day" article. The earlier float-based version (`floor(365.25 * (y+4716))`) off-by-ones for centuries divisible by 400 (the leap year exception interacts with the constant 0.25 in a way the floor doesn't round correctly for), so we use the canonical integer form. """ y, m, d = g.year, g.month, g.day a = (14 - m) // 12 y = y + 4800 - a m = m + 12 * a - 3 return d + (153 * m + 2) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045
@dataclassclass HijriDate: """A point on the Islamic lunar calendar.""" day: int month: int year: int month_name: str
def __str__(self) -> str: return f"{self.day} {self.month_name} {self.year} AH"
def to_dict(self) -> dict: return { "day": self.day, "month": self.month, "year": self.year, "month_name": self.month_name, "formatted": str(self), }
# The Islamic epoch is 16 July 622 CE in the Julian calendar. In# the proleptic-Gregorian JDN used by our `_julian_day` function,# using civil epoch JDN 1948440 aligns the tabular fallback cleanly# with standard civil calendars and verified 1446–1449 regional anchors._ISLAMIC_EPOCH_JD = 1948440
def gregorian_to_hijri(g: datetime.date) -> HijriDate: """Convert a Gregorian date to its Hijri equivalent.
Uses the standard Reingold-Dershowitz algorithm. The result is the Hijri date as it would appear on a civil calendar for that Gregorian day; in practice the religious Hijri date is set by moon sighting and may differ by ±1 day in some locations. """ days_since_epoch = _julian_day(g) - _ISLAMIC_EPOCH_JD if days_since_epoch < 0: return HijriDate(day=1, month=1, year=1, month_name=HIJRI_MONTHS[0])
# 30-year cycle = 10631 days. Find the year by integer division # using the cycle's average length. year = 1 + (30 * days_since_epoch + 10630) // 10631
# Refine: if `year` is too low, advance. (The cycle math can be # off by one in either direction at the boundary.) while _hijri_to_absolute_days(year, 1, 1) > days_since_epoch: year -= 1 while _hijri_to_absolute_days(year + 1, 1, 1) <= days_since_epoch: year += 1
# Find the month within `year`. year_start = _hijri_to_absolute_days(year, 1, 1) day_of_year = days_since_epoch - year_start # 0-indexed days_so_far = 0 for m in range(1, 13): m_days = _hijri_month_days(year, m) if day_of_year < days_so_far + m_days: return HijriDate( day=day_of_year - days_so_far + 1, month=m, year=year, month_name=HIJRI_MONTHS[m - 1], ) days_so_far += m_days
# Unreachable for valid input, but keep a defensive fallback. return HijriDate( day=_hijri_month_days(year, 12), month=12, year=year, month_name=HIJRI_MONTHS[11], )
def format_gregorian(g: datetime.date) -> str: """Format a Gregorian date in the same shape as the rest of the app (e.g. '07 June 2026').""" months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ] return f"{g.day:02d} {months[g.month - 1]} {g.year}"12345678910111213"""Backward-compatible proxy for rag.rerank"""from app.rag.rerank import *from app.rag.rerank import ( _prob_to_logit, _openrouter_embed, _cloud_rerank, _normalize_reranker_score, _parse_reranker_response, close_rerank_clients,)
123456"""Backward-compatibility proxy for app.infrastructure.mongodbProvides seamless import resolution for any code importing app.infrastructure.database"""
from .mongodb import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Firebase Infrastructure ClientManages Firebase Admin SDK initialization, lifecycle, and server-side token verification."""import osimport timeimport jsonimport base64import loggingfrom typing import Optional, Dict, Anyfrom fastapi import HTTPException, statusimport firebase_adminfrom firebase_admin import credentials, auth as firebase_auth
logger = logging.getLogger("sahihislam.firebase")
_firebase_initialized = False_has_service_account = False
def has_service_account_credentials() -> bool: """Returns True if Firebase Admin was initialized with real Service Account credentials.""" return _has_service_account and bool(firebase_admin._apps)
def _load_credentials_dict() -> Optional[Dict[str, Any]]: """ Attempts to discover and load Firebase service account credentials from environment variables (JSON string, base64, or file path) or disk files. """ # 1. Check known environment variable names candidate_keys = [ "FIREBASE_CREDENTIALS_JSON", "FIREBASE_JSON_STRING", "FIREBASE_CREDENTIALS", "FIREBASE_ADMIN_CREDENTIALS", "FIREBASE_SERVICE_ACCOUNT", "FIREBASE_SERVICE_ACCOUNT_KEY", "FIREBASE_CONFIG", "GOOGLE_APPLICATION_CREDENTIALS_JSON", "GOOGLE_APPLICATION_CREDENTIALS", ]
raw_val: Optional[str] = None for key in candidate_keys: val = os.getenv(key) if val and val.strip(): raw_val = val.strip() logger.info("Found Firebase credentials candidate in environment variable: %s", key) break
# 2. If not found in known keys, scan all environment variables for service account markers if not raw_val: for k, v in os.environ.items(): if v and isinstance(v, str) and ("service_account" in v and "private_key" in v): raw_val = v.strip() logger.info("Auto-discovered Firebase service account credentials in environment variable: %s", k) break
# 3. Check if raw_val is an existing file path if raw_val and os.path.exists(raw_val) and os.path.isfile(raw_val): try: with open(raw_val, "r", encoding="utf-8") as f: logger.info("Loaded Firebase credentials from file path: %s", raw_val) return json.load(f) except Exception as e: logger.warning("Failed to parse Firebase credentials from file %s: %s", raw_val, e)
# 4. Check if raw_val is a JSON string or base64 encoded JSON if raw_val: # Check base64 decoding if not starting with { if not raw_val.startswith("{"): try: decoded = base64.b64decode(raw_val).decode("utf-8") if decoded.strip().startswith("{"): raw_val = decoded.strip() except Exception: pass
# Clean any accidental outer shell quotes cleaned = raw_val.strip() if (cleaned.startswith("'") and cleaned.endswith("'")) or (cleaned.startswith('"') and cleaned.endswith('"')): cleaned = cleaned[1:-1].strip()
if cleaned.startswith("{") and cleaned.endswith("}"): try: data = json.loads(cleaned) if isinstance(data, dict) and "type" in data: logger.info("Successfully parsed Firebase credentials from environment JSON string") return data except Exception as e: logger.warning("Failed to parse JSON string in Firebase credentials env: %s", e)
# 5. Fallback to candidate file paths on disk base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) candidate_paths = [ "firebase_credentials.json", os.path.join(base_dir, "firebase_credentials.json"), os.path.join(base_dir, "app", "firebase_credentials.json"), os.path.join(base_dir, "BACKEND", "firebase_credentials.json"), "/app/firebase_credentials.json", ] for path in candidate_paths: if os.path.exists(path) and os.path.isfile(path): try: with open(path, "r", encoding="utf-8") as f: logger.info("Loaded Firebase credentials from file: %s", path) return json.load(f) except Exception as e: logger.warning("Failed to read credentials from %s: %s", path, e)
return None
def init_firebase() -> bool: """Initialize Firebase Admin SDK safely and idempotently.""" global _firebase_initialized, _has_service_account if _firebase_initialized and firebase_admin._apps: return True
if firebase_admin._apps: _firebase_initialized = True return True
try: cred_dict = _load_credentials_dict() if cred_dict: # Fix escaped newlines in RSA private key if needed if "private_key" in cred_dict and isinstance(cred_dict["private_key"], str): cred_dict["private_key"] = cred_dict["private_key"].replace("\\n", "\n")
cred = credentials.Certificate(cred_dict) firebase_admin.initialize_app(cred) _firebase_initialized = True _has_service_account = True logger.info("✅ Firebase Admin Initialized with service account: %s", cred_dict.get("client_email")) return True
# Fallback initialization when no service account is available (prevents empty _apps ValueError) project_id = ( os.getenv("FIREBASE_PROJECT_ID") or os.getenv("GOOGLE_CLOUD_PROJECT") or "sahih-islam-app" ) logger.warning( "⚠️ No Firebase service account file or JSON secret found. Initializing fallback app with projectId: %s", project_id, ) firebase_admin.initialize_app(options={"projectId": project_id}) _firebase_initialized = True return True
except Exception as e: logger.error("❌ Firebase Initialization Exception: %s", e, exc_info=True) # Even on exception, ensure default app is registered if not present if not firebase_admin._apps: try: firebase_admin.initialize_app(options={"projectId": "sahih-islam-app"}) _firebase_initialized = True return True except Exception: pass return False
_AUTH_LOG_WINDOW: Dict[str, float] = {}_AUTH_LOG_COOLDOWN = 5.0 # seconds between duplicate auth warning logs
def _log_auth_warning_rate_limited(category: str, summary: str): """Logs sanitized auth warning with cooldown to prevent log pollution and credential exposure.""" now = time.time() last = _AUTH_LOG_WINDOW.get(category, 0.0) if now - last >= _AUTH_LOG_COOLDOWN: _AUTH_LOG_WINDOW[category] = now logger.warning("auth: %s", summary)
def verify_firebase_token(token: str) -> Dict[str, Any]: """ Verifies a Firebase ID token. Returns the decoded claims dictionary. Supports mock/test tokens for benchmark/load simulation. Guarantees clean HTTP 401 exceptions on any token verification error. """ if not token or not isinstance(token, str) or not token.strip(): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing or empty authentication token", headers={"WWW-Authenticate": "Bearer"}, )
token = token.strip()
# Instant local evaluation for stress testing / mock personas (SEC-002: strictly gated by ALLOW_MOCK_AUTH) from app.core.config import settings if getattr(settings, "ALLOW_MOCK_AUTH", False) and any(token.lower().startswith(p) for p in ("mock", "test", "dev", "locust", "sim")): return { "uid": token, "email": f"{token}@sahihislam.local", "name": f"Persona {token[-8:]}", "role": "ADMIN" if "admin" in token.lower() else "USER", }
init_firebase()
try: return firebase_auth.verify_id_token(token, check_revoked=True, clock_skew_seconds=60) except firebase_auth.ExpiredIdTokenError: _log_auth_warning_rate_limited("expired_token", "Firebase ID token expired") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Firebase token expired", headers={"WWW-Authenticate": "Bearer"}, ) except firebase_auth.RevokedIdTokenError: _log_auth_warning_rate_limited("revoked_token", "Firebase ID token revoked") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Firebase token revoked", headers={"WWW-Authenticate": "Bearer"}, ) except firebase_auth.InvalidIdTokenError as e: _log_auth_warning_rate_limited("invalid_token", f"Invalid Firebase ID token ({type(e).__name__})") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Firebase ID token", headers={"WWW-Authenticate": "Bearer"}, ) except ValueError as e: _log_auth_warning_rate_limited("value_error", f"Malformed token syntax ({type(e).__name__})") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Malformed or unverified token", headers={"WWW-Authenticate": "Bearer"}, ) except Exception as e: logger.error("auth: Unexpected token verification error (%s): %s", type(e).__name__, e) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication failed: Invalid or expired token", headers={"WWW-Authenticate": "Bearer"}, )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511import os
import sys
import urllib.parse
import logging
logger = logging.getLogger(__name__)
try:
import dns.resolver
dns.resolver.default_resolver = dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers = ['8.8.8.8', '1.1.1.1']
except Exception:
pass
from motor.motor_asyncio import AsyncIOMotorClient
from dotenv import load_dotenv
load_dotenv()
if not os.getenv("MONGO_URI"):
for cand in [
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env"),
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env"),
os.path.join(os.getcwd(), "BACKEND", ".env"),
os.path.join(os.getcwd(), ".env"),
]:
if os.path.exists(cand):
load_dotenv(cand)
if os.getenv("MONGO_URI"):
break
# =========================================================
# 1. SECURE MONGODB CONNECTION SETUP (CENTRALIZED CONFIG)
# =========================================================
from app.core.config import settings
MONGO_URI = settings.MONGO_URI
if not MONGO_URI and settings.IS_PROD:
print("❌ CRITICAL ERROR: MONGO_URI / MONGODB_URI environment variable is missing. Server shutting down.")
sys.exit(1)
# =========================================================
# 2. ASYNC DATABASE SINGLETON (PRODUCTION TUNED)
# =========================================================
class AsyncDatabase:
_instance = None
_client = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(AsyncDatabase, cls).__new__(cls)
# 🚀 ENTERPRISE CONNECTION POOLING (Resilient Atlas M0/Dedicated Elastic Pool Sizing)
from app.core.config import settings
_max_pool = settings.MONGO_MAX_POOL_SIZE
_min_pool = settings.MONGO_MIN_POOL_SIZE
_wait_timeout = settings.MONGO_WAIT_QUEUE_TIMEOUT_MS
cls._client = AsyncIOMotorClient(
MONGO_URI,
maxPoolSize=_max_pool,
minPoolSize=_min_pool,
maxIdleTimeMS=45000,
waitQueueTimeoutMS=_wait_timeout,
connectTimeoutMS=8000,
serverSelectionTimeoutMS=5000,
retryWrites=True
)
print(f"[DATABASE] Enterprise Async Connection Pool Initialized (Tuned: {_max_pool} max, {_min_pool} min, {_wait_timeout}ms queue timeout)")
return cls._instance
@property
def client(self):
return self._client
@property
def db(self):
# Environment-isolated primary user and sacred text database
from app.core.config import settings
return self._client[settings.MONGO_DB_NAME]
@property
def db_admin(self):
# Environment-isolated SuperAdmin control plane & governance database
from app.core.config import settings
return self._client[settings.MONGO_DB_ADMIN_NAME]
@property
def db_commerce(self):
# Environment-isolated financial ledger, ads & marketplace database
from app.core.config import settings
return self._client[settings.MONGO_DB_COMMERCE_NAME]
@classmethod
def close(cls):
"""Closes the underlying Motor client connection pool."""
if cls._client is not None:
try:
cls._client.close()
except Exception:
pass
cls._client = None
cls._instance = None
async def close_db():
"""Gracefully closes MongoDB connection pool."""
try:
AsyncDatabase.close()
print("🛑 [DATABASE] MongoDB connection pool closed gracefully.")
except Exception as e:
print(f"⚠️ [DATABASE] Error closing MongoDB connection: {e}")
# 🚀 INITIALIZE THE SINGLETON (Crucial: Must happen before defining collections)
db_instance = AsyncDatabase()
client = db_instance.client
db = db_instance.db
db_admin = db_instance.db_admin
db_commerce = db_instance.db_commerce
# =========================================================
# 3. DOMAIN-DRIVEN LOGICAL COLLECTIONS (ISOLATED EXPORTS)
# =========================================================
# ---------------------------------------------------------
# DOMAIN A: USER & APPLICATION DATA PLANE (sahihislam)
# Highly concurrent, read-heavy, low-latency client services
# Sacred scriptures with Atlas Search Vector Indexes
# ---------------------------------------------------------
users_collection = db["users"]
chats_collection = db["chats"]
hadith_collection = db["hadiths"]
quran_collection = db["quran"]
quran_verses_collection = db["quran_verses"]
masjid_collection = db["masjids"]
permanent_masjids_collection = db["permanent_masjids"]
masjid_events_collection = db["masjid_events"]
masjid_notifications_collection = db["masjid_notifications"]
notifications_collection = db["notifications"]
device_tokens_collection = db["device_tokens"]
# Spiritual telemetry & Personal user recordsdaily_progress_collection = db["daily_progress"]qaza_collection = db["qaza_tracker"]qaza_events_collection = db["qaza_events"]nimaz_stats_collection = db["nimaz_stats"]tasbeeh_collection = db["tasbeeh_records"]tasbeeh_daily_collection = db["tasbeeh_daily"]tasbeeh_stats_collection = db["tasbeeh_stats"]
# Unified Vector Memory & Shared Daily Content Pools
vector_memory_collection = db["vector_memory"]
daily_hadith_pool_collection = db["daily_hadith_pool"]
daily_ayah_pool_collection = db["daily_ayah_pool"]
daily_content_selection_collection = db["daily_content_selection"]
# ---------------------------------------------------------
# DOMAIN B: SUPERADMIN CONTROL PLANE & PLATFORM GOVERNANCE (sahihislam_admin)
# Master platform configurations, approvals, and feature gates
# ---------------------------------------------------------
system_settings_collection = db_admin["system_settings"]
platform_settings_collection = db_admin["platform_settings"]
staff_permissions_collection = db_admin["staff_permissions"]
sendads_collection = db_admin["sendads"]
pending_approvals_collection = db_admin["pending_approvals"]
verified_role_records_collection = db_admin["verified_role_records"]
mufti_hadiths_collection = db_admin["mufti_hadiths"]
mufti_requests_collection = db_admin["mufti_requests"]
masjid_reports_collection = db_admin["masjid_reports"]
# ---------------------------------------------------------
# DOMAIN C: OBSERVABILITY, AUDIT & TELEMETRY (sahihislam_admin)
# Administrative audit trails and client runtime telemetry
# ---------------------------------------------------------
audit_logs_collection = db_admin["audit_logs"]ai_response_reports_collection = db_admin["ai_response_reports"]
client_errors_collection = db_admin["client_errors"]
deleted_masjids_audit_collection = db_admin["deleted_masjids_audit"]
email_change_requests_collection = db_admin["email_change_requests"]
email_change_logs_collection = db_admin["email_change_logs"]
search_analytics_collection = db_admin["search_analytics"]
admin_bootstrap_lock_collection = db_admin["admin_bootstrap_lock"]
contact_messages_collection = db_admin["contact_messages"]
# ---------------------------------------------------------
# DOMAIN D: FINANCIAL LEDGER, ADS & MARKETPLACE (sahihislam_commerce)
# Immutable transactional balances and commerce
# ---------------------------------------------------------
ads_collection = db_commerce["ads"]
ad_analytics_collection = db_commerce["ad_analytics"]
admob_telemetry_collection = db_commerce["admob_telemetry"]
products_collection = db_commerce["products"]
orders_collection = db_commerce["orders"]checkout_operations_collection = db_commerce["checkout_operations"]
wallets_collection = db_commerce["wallets"]
transactions_collection = db_commerce["transactions"]payment_orders_collection = db_commerce["payment_orders"]ai_quota_daily_collection = db["ai_quota_daily"]
payouts_collection = db_commerce["payouts"]
shop_settings_collection = db_commerce["shop_settings"]shops_collection = db_commerce["shops"]
subscriptions_collection = db_commerce["subscriptions"]
refund_requests_collection = db_commerce["refund_requests"]
# Dedicated, non-TTL collections for durable financial idempotency, auditability & webhook deduplication (NEW-10, NEW-14)financial_idempotency_collection = db_commerce["financial_idempotency"]financial_audit_logs_collection = db_commerce["financial_audit_logs"]processed_webhook_events_collection = db_commerce["processed_webhook_events"]
# =========================================================
# 4. ASYNC INDEXING & VALIDATION
# =========================================================
# ---------------------------------------------------------------
# 4a. Atlas Vector Search index definitions
# ---------------------------------------------------------------
# These are NOT standard B-tree indexes — they live in Atlas Search.
# You create them with `db.command({"createSearchIndexes": ...})`
# (the `create_index` API does NOT work for vector search).
#
# Naming MUST match what hadith.py references, or the $vectorSearch
# stage will fail with "Index not found":
# hadith.py → "sahihislam1024_index" on hadith_collection.embedding
# hadith.py → "unified_memory1024_index" on vector_memory_collection.embedding_1024
# hadith.py → "quran1024_index" on quran_verses_collection.embedding_1024
#
# Dimensions: bge-m3 (dense 1024-dim embedding model) produces
# 1024-dim vectors. Everything in this stack is 1024-d.
# Similarity: cosine (correct for normalized sentence-transformer output).
# Filters: declare every field we ever pass in a runtime `filter`
# clause as filterable — otherwise $vectorSearch with a
# filter will reject the query.
# • hadith_collection → filters by "collection"
# • vector_memory_collection → filters by "memory_type",
# "user_id", "session_id", "language", "top_k"
# • quran_verses_collection → no runtime filter today
_VECTOR_INDEX_SPECS = {
hadith_collection: {
"name": "vector_index",
"type": "vectorSearch",
"definition": {
"fields": [
{
"type": "vector",
"path": "embedding_1024",
"numDimensions": 1024,
"similarity": "cosine",
},
# Pre-declare filterable fields so $vectorSearch with a
# `filter: { collection: {...} }` clause is accepted.
{"type": "filter", "path": "collection"},
{"type": "filter", "path": "grade"},
{"type": "filter", "path": "book_no"},
],
},
},
vector_memory_collection: {
"name": "unified_memory1024_index",
"type": "vectorSearch",
"definition": {
"fields": [
{
"type": "vector",
"path": "embedding_1024",
"numDimensions": 1024,
"similarity": "cosine",
},
{"type": "filter", "path": "memory_type"},
{"type": "filter", "path": "user_id"},
{"type": "filter", "path": "session_id"},
{"type": "filter", "path": "language"},
{"type": "filter", "path": "top_k"},
{"type": "filter", "path": "collection_scope"},
{"type": "filter", "path": "strict_mode"},
],
},
},
quran_verses_collection: {
"name": "quran1024_index",
"type": "vectorSearch",
"definition": {
"fields": [
{
"type": "vector",
"path": "embedding_1024",
"numDimensions": 1024,
"similarity": "cosine",
},
],
},
},
}
async def _ensure_vector_index(collection, spec: dict) -> None:
"""
Create an Atlas Vector Search index if it doesn't exist; treat
"already exists" as success. MongoDB's `createSearchIndexes` raises
IndexAlreadyExists (code 68) if a same-named index is already there —
that's the same outcome we want, so we swallow it.
"""
name = spec["name"]
try:
await db.command({
"createSearchIndexes": collection.name,
"indexes": [{
"name": name,
"type": spec["type"],
"definition": spec["definition"],
}],
})
print(f" ✅ vector[{collection.name}.{name}] created "
f"({spec['definition']['fields'][0]['numDimensions']}d, "
f"{spec['definition']['fields'][0]['similarity']})")
except Exception as e:
msg = str(e)
# Already exists — that's fine, the index is in place.
if "IndexAlreadyExists" in msg or "already defined" in msg or "code': 68" in msg:
print(f" • vector[{collection.name}.{name}] already exists, leaving as-is")
return
# Server has no concept of search indexes at all — self-hosted
# Mongo without the search subsystem. $vectorSearch will fail at
# runtime; tell the operator loudly.
if "CommandNotFound" in msg or "command not found" in msg.lower():
print(f" ⚠️ vector[{collection.name}.{name}] NOT created: "
f"this MongoDB does not support Atlas Search. $vectorSearch "
f"will fail at runtime. Use Atlas (free M0 works) or a "
f"server with the search subsystem enabled.")
return
# Anything else: surface it.
print(f" ❌ vector[{collection.name}.{name}] create failed: {e}")
async def init_db_indexes():
try:
await db.command("ping")
await db_admin.command("ping")
await db_commerce.command("ping")
print("✅ MongoDB Connected: [sahihislam, sahihislam_admin, sahihislam_commerce] Pinged Successfully.")
# ========== USERS (Enterprise Architecture & Analytics) ==========
await users_collection.create_index("uid", unique=True)
await users_collection.create_index("email", unique=True)
await users_collection.create_index("auth.role")
await users_collection.create_index("auth.status")
await users_collection.create_index("business.is_enabled")
await users_collection.create_index("community.masjid.managed_masjid_id")
await users_collection.create_index("community.masjid.followed_masjids")
await users_collection.create_index("analytics.signup_platform")
await users_collection.create_index("analytics.created_at")
await users_collection.create_index("analytics.last_active_at")
await users_collection.create_index([("created_at", -1)])
await users_collection.create_index("role")
await users_collection.create_index("is_pro")
# ========== CHATS ==========
# Compound: chat history listing filters by user_id and sorts by
# last_updated desc — a single-field index can't serve both, so a
# compound makes the query fully index-backed.
await chats_collection.create_index(
[("user_id", 1), ("last_updated", -1)],
name="chats_user_recent_idx",
)
# Upsert hot-path: vectorize_and_save_memory does an upsert keyed
# on (user_id, session_id). A unique compound guarantees the
# upsert targets one document and skips the extra existence check.
await chats_collection.create_index(
[("user_id", 1), ("session_id", 1)],
name="chats_user_session_idx",
unique=True,
)
# ========== MASJID (Enterprise Architecture & Geo) ==========
await masjid_collection.create_index("id")
await masjid_collection.create_index("masjid_id", unique=True)
await masjid_collection.create_index([("created_at", -1)])
await masjid_collection.create_index("status")
await masjid_collection.create_index("admin_uid")
await masjid_collection.create_index("co_admins")
await masjid_collection.create_index("fiqh")
await masjid_collection.create_index("administration.admin_uid")
await masjid_collection.create_index("administration.status")
await masjid_collection.create_index("identity.is_verified")
await masjid_collection.create_index("identity.fiqh")
await masjid_collection.create_index("address.district")
await masjid_collection.create_index("address.country")
await masjid_collection.create_index("metrics.followers_count")
await masjid_collection.create_index("audit.created_at")
await masjid_collection.create_index("audit.last_timings_updated_at")
# 2dsphere index enables $near / $geoWithin proximity queries # for the /masjid/nearby endpoint (standard GeoJSON Point on `location`). try: await masjid_collection.create_index( [("location", "2dsphere")], name="masjid_location_2dsphere", ) await permanent_masjids_collection.create_index( [("geo_location", "2dsphere")], sparse=True, name="perm_masjid_geo_location_2dsphere", ) except Exception as _geo_e: if "IndexAlreadyExists" not in str(_geo_e) and "already defined" not in str(_geo_e): print(f"⚠️ masjid 2dsphere index: {_geo_e}")
# Scheduled notifications due-query compound index (PX-25) try: await notifications_collection.create_index( [("status", 1), ("scheduled_time", 1)], name="notifications_status_scheduled_time_idx", ) except Exception: pass
try:
await permanent_masjids_collection.create_index(
[("location", "2dsphere")],
name="permanent_masjid_location_2dsphere",
)
await permanent_masjids_collection.create_index("masjid_id", unique=True)
await permanent_masjids_collection.create_index("is_live")
except Exception as _p_e:
if "IndexAlreadyExists" not in str(_p_e) and "already defined" not in str(_p_e):
print(f"⚠️ permanent_masjids 2dsphere index: {_p_e}")
# ========== MASJID REPORTS ==========
# One report per user per masjid: a unique compound makes the
# "report" action idempotent (a user can't inflate the count by
# reporting the same masjid repeatedly).
await masjid_reports_collection.create_index(
[("masjid_id", 1), ("uid", 1)],
name="masjid_report_unique_idx",
unique=True,
)
# Listing/counting reports for a masjid (admin reports tab).
await masjid_reports_collection.create_index("masjid_id")
# ========== DAILY PROGRESS / STREAK ==========
# One doc per (uid, local-date). Unique compound keeps the
# upsert targeting a single doc and makes the streak look-back
# (range scan over a user's recent dates) index-backed. await daily_progress_collection.create_index( [("uid", 1), ("date", -1)], name="progress_uid_date_idx", unique=True, ) await daily_progress_collection.create_index( [("uid", 1), ("is_full", 1)], name="progress_uid_is_full_idx", ) await daily_progress_collection.create_index( [("uid", 1), ("is_golden", 1)], name="progress_uid_is_golden_idx", ) await nimaz_stats_collection.create_index( [("uid", 1)], name="nimaz_stats_uid_idx", unique=True, ) await qaza_collection.create_index( [("uid", 1)], name="qaza_uid_idx", )
await daily_content_selection_collection.create_index(
[("content_type", 1), ("date", -1)],
name="daily_content_type_date_idx",
)
# ========== TASBEEH & DHIKR LIFETIME ARCHITECTURE ==========
await tasbeeh_collection.create_index(
[("uid", 1), ("date", -1)],
name="tasbeeh_uid_date_idx"
)
await tasbeeh_collection.create_index(
[("uid", 1), ("timestamp", -1)],
name="tasbeeh_uid_timestamp_idx"
)
await tasbeeh_collection.create_index(
[("uid", 1), ("event_id", 1)],
name="tasbeeh_uid_event_idx"
)
await tasbeeh_collection.create_index(
[("uid", 1), ("dhikr", 1)],
name="tasbeeh_uid_dhikr_idx"
)
await tasbeeh_daily_collection.create_index(
[("uid", 1), ("date", -1)],
name="tasbeeh_daily_uid_date_idx",
unique=True
)
await tasbeeh_daily_collection.create_index(
[("uid", 1), ("total_count", -1)],
name="tasbeeh_daily_uid_total_idx"
)
await tasbeeh_stats_collection.create_index(
"uid",
name="tasbeeh_stats_uid_idx",
unique=True
)
# ========== MASJID EVENTS (Enhanced Architecture) ==========
# Index for fetching events by masjid
await masjid_events_collection.create_index("masjid_id")
# Index for sorting by date (upcoming events first)
await masjid_events_collection.create_index("start_datetime")
# Index for sorting by popularity (likes & RSVP)
await masjid_events_collection.create_index("likes_count")
await masjid_events_collection.create_index("going_count")
# Index for filtering by category, fiqh, status
await masjid_events_collection.create_index("category")
await masjid_events_collection.create_index("fiqh")
await masjid_events_collection.create_index("status")
await masjid_events_collection.create_index("created_by")
await masjid_events_collection.create_index("created_at")
# ========== MASJID NOTIFICATIONS (Broadcast & Alerts) ==========
await masjid_notifications_collection.create_index([("masjid_id", 1), ("created_at", -1)])
await masjid_notifications_collection.create_index("notification_id", unique=True)
# ========== ENTERPRISE DEVICE TOKENS (FCM PUSH SCALABILITY) ========== await device_tokens_collection.create_index("token", unique=True) await device_tokens_collection.create_index([("uid", 1), ("updated_at", -1)]) await device_tokens_collection.create_index([("uid", 1), ("device_id", 1)]) await device_tokens_collection.create_index([("platform", 1), ("updated_at", -1)]) await device_tokens_collection.create_index([("topics", 1), ("last_seen_at", -1)]) await device_tokens_collection.create_index( "last_seen_at", expireAfterSeconds=90 * 24 * 60 * 60, # Auto-prune stale 90-day inactive tokens )
# Compound index for efficient masjid event queries
try:
await masjid_events_collection.drop_index("events_masjid_date_idx")
except Exception:
pass
await masjid_events_collection.create_index(
[("masjid_id", 1), ("start_datetime", 1)],
name="events_masjid_start_datetime_idx",
)
# Compound index for sorting by popularity and date
await masjid_events_collection.create_index(
[("likes_count", -1), ("start_datetime", 1)],
name="events_popularity_idx",
)
# Compound index for active upcoming events
await masjid_events_collection.create_index(
[("status", 1), ("start_datetime", 1)],
name="events_status_start_datetime_idx",
)
# ========== HADITH ==========
# Fast filter-by-grade (used by strict-mode lookups).
await hadith_collection.create_index("grade")
# The compound on (hadith_id, collection) matches both
# - exact-match lookups in /auth (auth.py:352)
# - the unique-key probe in (hadith_id, collection) is also a
# natural sort key.
# No `name=` — let Mongo auto-name so re-running init_db_indexes()
# on a DB where this index already exists under its auto-name
# doesn't fail with IndexOptionsConflict.
await hadith_collection.create_index(
[("hadith_id", 1), ("collection", 1)],
)
# NEW: Compound used by get_hadiths_final (auth.py:301) —
# find({collection, volume, book_no}).sort("hadith_id")
# The volume+book_no are checked with $in against both str and int
# representations, so a compound on (collection, volume, book_no)
# lets Mongo walk the index range instead of COLLSCAN.
# Wrapped in try/except: Atlas may already have this index under
# the auto-generated name 'collection_1_volume_1_book_no_1'
# (IndexOptionsConflict code 85) — treat that as success.
try:
await hadith_collection.create_index(
[("collection", 1), ("volume", 1), ("book_no", 1)],
name="hadith_collection_volume_book_idx",
)
except Exception as _hidx_e:
_hidx_msg = str(_hidx_e)
if "85" in _hidx_msg or "IndexOptionsConflict" in _hidx_msg or "already exists" in _hidx_msg:
print(" • hadith compound index already exists under different name — skipping")
else:
raise
try:
await hadith_collection.create_index(
[("collection", 1), ("volume", 1), ("book_no", 1), ("hadith_id", 1)],
name="hadith_collection_vol_book_id_idx",
)
except Exception:
pass
# Full-text search index for keyword queries.
await hadith_collection.create_index(
[("text_english", "text"), ("collection", "text")],
name="hadith_text_index",
)
await hadith_collection.create_index([("collection", 1), ("book_no", 1)])
await hadith_collection.create_index("book_name")
# ========== QURAN & VERSES ==========
try:
await quran_collection.create_index("surah_no", unique=True)
except Exception:
await quran_collection.create_index("surah_no")
await quran_verses_collection.create_index([("surah_no", 1), ("verse_no", 1)])
# ========== VECTOR MEMORY (B-tree side) ==========
# Already had memory_type + (user_id, session_id) — kept as-is.
await vector_memory_collection.create_index([("memory_type", 1)])
await vector_memory_collection.create_index(
[("user_id", 1), ("session_id", 1)],
)
# Used for cache-eviction / "oldest global cache" sweeps.
await vector_memory_collection.create_index([("timestamp", -1)])
# DATA-001: Automatic Atlas M0 capacity preservation — TTL index expires AI embedding memory after 14 days (1,209,600s)
try:
await vector_memory_collection.create_index(
[("timestamp", 1)],
name="vector_memory_ttl_14d",
expireAfterSeconds=1209600,
background=True,
)
except Exception as _e:
logger.warning(f"Note on vector_memory TTL index: {_e}")
# ========== ADS & MARKETPLACE (100k+ Scale Tuned) ==========
# Ads collection indexes
await ads_collection.create_index("ad_id", unique=True)
await ads_collection.create_index("advertiser_uid")
await ads_collection.create_index("status")
await ads_collection.create_index([("status", 1), ("daily_budget", -1), ("spent", 1), ("budget", 1)])
await ads_collection.create_index([("status", 1), ("start_date", 1), ("end_date", 1), ("daily_budget", -1)])
await ads_collection.create_index([("status", 1), ("category", 1), ("daily_budget", -1)])
await ads_collection.create_index("category")
await ads_collection.create_index("created_at")
# Products collection indexes
await products_collection.create_index("product_id", unique=True)
await products_collection.create_index("seller_uid")
await products_collection.create_index("status")
await products_collection.create_index("category")
await products_collection.create_index([("category", 1), ("price", 1)])
await products_collection.create_index([("seller_uid", 1), ("created_at", -1)])
# Text search for products
await products_collection.create_index(
[("title", "text"), ("description", "text"), ("tags", "text")],
name="products_text_search"
)
# Ad analytics indexes
await ad_analytics_collection.create_index([("ad_id", 1), ("date", -1)])
await ad_analytics_collection.create_index([("ad_id", 1), ("event_type", 1), ("timestamp", -1)])
# AdMob telemetry indexes
await admob_telemetry_collection.create_index([("timestamp", -1)])
await admob_telemetry_collection.create_index([("event_type", 1), ("timestamp", -1)])
await admob_telemetry_collection.create_index([("ad_format", 1), ("timestamp", -1)])
await admob_telemetry_collection.create_index("platform")
# Orders collection indexes
await orders_collection.create_index("order_id", unique=True)
await orders_collection.create_index("buyer_uid")
await orders_collection.create_index("seller_uid")
await orders_collection.create_index([("seller_uid", 1), ("created_at", -1)], background=True)
await orders_collection.create_index([("items.seller_uid", 1), ("created_at", -1)], background=True)
await orders_collection.create_index([("buyer_uid", 1), ("created_at", -1)])
await orders_collection.create_index("status")
# ========== WALLETS & TRANSACTIONS ==========
await wallets_collection.create_index("user_id", unique=True)
await transactions_collection.create_index("transaction_id", unique=True)
await transactions_collection.create_index("external_order_id", sparse=True)
await transactions_collection.create_index([("user_id", 1), ("created_at", -1)])
await transactions_collection.create_index([("user_id", 1), ("type", 1), ("created_at", -1)])
await transactions_collection.create_index([("tag", 1), ("created_at", -1)])
await transactions_collection.create_index([("tag", 1), ("type", 1), ("created_at", -1)])
await transactions_collection.create_index("reference_id")
await transactions_collection.create_index("status")
await subscriptions_collection.create_index("user_id", unique=True)
await subscriptions_collection.create_index("purchase_token", unique=True, sparse=True)
await subscriptions_collection.create_index([("tag", 1), ("created_at", -1)])
await shop_settings_collection.create_index("seller_uid", unique=True)
await refund_requests_collection.create_index("request_id", unique=True)
await refund_requests_collection.create_index([("user_id", 1), ("created_at", -1)])
await refund_requests_collection.create_index([("transaction_id", 1)])
await refund_requests_collection.create_index([("status", 1), ("created_at", -1)])
# Permanent Financial Idempotency & Audit Trails (NO TTL expiration) await financial_idempotency_collection.create_index("created_at") await financial_idempotency_collection.create_index([("operation_scope", 1), ("created_at", -1)]) await financial_idempotency_collection.create_index([("status", 1), ("lease_expires_at", 1)], sparse=True) await financial_idempotency_collection.create_index([("idempotency_key", 1), ("requester_uid", 1)], sparse=True) await financial_audit_logs_collection.create_index("audit_id", unique=True, sparse=True) await financial_audit_logs_collection.create_index([("action", 1), ("timestamp", -1)]) await financial_audit_logs_collection.create_index([("entity_type", 1), ("entity_id", 1)]) await financial_audit_logs_collection.create_index([("target_user_id", 1), ("timestamp", -1)], sparse=True) await financial_audit_logs_collection.create_index([("admin_uid", 1), ("timestamp", -1)], sparse=True) await processed_webhook_events_collection.create_index("event_id", unique=True) await processed_webhook_events_collection.create_index("refund_id", sparse=True) await processed_webhook_events_collection.create_index([("status", 1), ("lease_expires_at", 1)], sparse=True) await processed_webhook_events_collection.create_index("created_at")
# ========== CLIENT RUNTIME ERROR LOGS ==========
await client_errors_collection.create_index("fingerprint", unique=True)
await client_errors_collection.create_index([("last_seen", -1)])
await client_errors_collection.create_index([("category", 1), ("status", 1)])
await client_errors_collection.create_index([("total_occurrences", -1)])
try:
await client_errors_collection.create_index(
"last_seen_date",
expireAfterSeconds=5184000, # 60 days TTL auto-purge
name="client_errors_ttl_60d_idx"
)
except Exception:
pass
# ========== DOMAIN B & C: CONTROL PLANE & AUDIT LOGS ==========
# 1. System Settings Primary Index
await system_settings_collection.create_index("_id")
await staff_permissions_collection.create_index("uid", unique=True)
await staff_permissions_collection.create_index("email", unique=True)
await staff_permissions_collection.create_index("is_active")
# 2. Audit Logs TTL Auto-Purge (90-day retention to prevent disk bloat)
try:
await audit_logs_collection.create_index(
"created_at",
expireAfterSeconds=7776000, # 90 days TTL
name="audit_logs_ttl_90d_idx"
)
except Exception:
pass
# 3. Fast Compound Filtering for SuperAdmin Audit Logs Portal
await audit_logs_collection.create_index(
[("admin_uid", 1), ("action", 1), ("timestamp", -1)],
name="audit_logs_admin_action_ts_idx"
)
await audit_logs_collection.create_index(
[("timestamp", -1)],
name="audit_logs_timestamp_desc_idx"
)
await audit_logs_collection.create_index("action")
await audit_logs_collection.create_index("entity_type") await ai_response_reports_collection.create_index([("status", 1), ("created_at", -1)]) await ai_response_reports_collection.create_index("user_id")
# 4. Search & Cache Analytics Indexing
await search_analytics_collection.create_index([("date", -1)], unique=True)
await search_analytics_collection.create_index([("year_month", -1)])
await search_analytics_collection.create_index("year")
await search_analytics_collection.create_index("month")
# ========== CONTACT MESSAGES (SI-SEC-017 / NEW-014 Retention) ==========
await contact_messages_collection.create_index("ticket_id", unique=True)
await contact_messages_collection.create_index([("created_at", -1)])
try:
await contact_messages_collection.create_index(
"created_at",
expireAfterSeconds=7776000, # 90-day auto-purge for believer privacy & retention compliance
name="contact_messages_ttl_90d_idx"
)
except Exception:
pass
# ========== AI DAILY QUOTA (P2-REDIS-01) ========== await ai_quota_daily_collection.create_index([("uid", 1), ("day", 1)], unique=True) try: await ai_quota_daily_collection.create_index( "created_at", expireAfterSeconds=604800, # 7-day auto-purge name="ai_quota_daily_ttl_7d_idx" ) except Exception: pass
# ========== AADS TRACKING NONCES (Distributed Anti-Replay) ========== await db["ad_tracking_nonces"].create_index("nonce", unique=True) try: await db["ad_tracking_nonces"].create_index( "created_at", expireAfterSeconds=86400, # 24h auto-purge name="ad_tracking_nonces_ttl_24h_idx" ) except Exception: pass
# ========== CHECKOUT IDEMPOTENCY UNIQUE INDEXES (PX-09 / PX-19) ========== try: await orders_collection.create_index( [("buyer_uid", 1), ("idempotency_key", 1)], unique=True, partialFilterExpression={"idempotency_key": {"$type": "string"}}, name="orders_buyer_idempotency_unique_idx", ) await checkout_operations_collection.create_index( [("user_id", 1), ("idempotency_key", 1)], unique=True, partialFilterExpression={"idempotency_key": {"$type": "string"}}, name="checkout_ops_user_idempotency_unique_idx", ) except Exception as idx_err: logger.error(f"Critical financial unique index creation failed: {idx_err}") raise
# ========== ATLAS VECTOR SEARCH INDEXES ==========
# These are the 1024-dim indexes actually referenced by hadith.py
# (sahihislam1024_index, unified_memory1024_index, quran1024_index)
# — without them, $vectorSearch raises at runtime.
print("⚡ Ensuring Atlas Vector Search indexes...")
for collection, spec in _VECTOR_INDEX_SPECS.items():
await _ensure_vector_index(collection, spec)
print("⚡ Enterprise Indexes Verified.")
except Exception as e:
logger.error(f"❌ MongoDB initialization error: {e}", exc_info=True) print(f"❌ MongoDB initialization error: {e}") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576"""Redis Enterprise Client for Sahih IslamSupports Upstash Serverless / Redis Cloud over TLS (rediss://)Includes automatic fallback to in-memory cache if Redis is unconfigured or unreachable,guaranteeing 100% zero-downtime uptime."""
import osimport timeimport loggingimport datetimefrom typing import Optional, Tuple, Dict, Anyfrom uuid import uuid4from dotenv import load_dotenvload_dotenv()
logger = logging.getLogger("sahih_redis")
try: import redis.asyncio as aioredis from redis.exceptions import RedisError REDIS_AVAILABLE = Trueexcept ImportError: aioredis = None RedisError = Exception REDIS_AVAILABLE = False
class RedisManager: def __init__(self): self._client: Optional[Any] = None self._url: str = os.getenv("REDIS_URL", "").strip() self._memory_cache: Dict[str, Tuple[str, float]] = {} # key -> (value, expire_timestamp) self._memory_counters: Dict[str, Tuple[int, float]] = {} # key -> (count, expire_timestamp) self._init_attempted: bool = False self._last_init_attempt: float = 0.0 self._init_retry_cooldown: float = float(os.getenv("REDIS_RECONNECT_COOLDOWN_SEC", "5.0"))
async def _ensure_client(self, *, force_retry: bool = False): """Lazy initialization with automatic periodic reconnect retries after transient failures.""" if self._client is not None: return configured_url = os.getenv("REDIS_URL", "").strip() or self._url if not configured_url: if not self._init_attempted: await self.init() return now = time.monotonic() if force_retry or not self._init_attempted or (now - self._last_init_attempt) >= self._init_retry_cooldown: await self.init()
async def init(self) -> bool: """Initialize Redis async client pool.""" self._init_attempted = True self._last_init_attempt = time.monotonic() self._url = os.getenv("REDIS_URL", "").strip() or self._url if not self._url: logger.info("ℹ️ REDIS_URL not configured. Operating in high-performance in-memory fallback mode.") return False
if not REDIS_AVAILABLE: logger.warning("⚠️ redis-py not installed. Falling back to in-memory mode.") return False
client = None try: # Handles rediss:// (TLS) and standard redis:// client = aioredis.from_url( self._url, encoding="utf-8", decode_responses=True, socket_timeout=6.0, socket_connect_timeout=6.0, retry_on_timeout=True, max_connections=100, ) # Ping to verify handshake await client.ping() self._client = client logger.info("🚀 Upstash/Cloud Redis Connection Established & Verified Successfully!") return True except Exception as e: logger.warning(f"⚠️ Redis connection failed ({e}). Gracefully falling back to in-memory cache.") if client is not None: try: await client.aclose() except Exception: pass self._client = None return False
async def close(self): """Close connection cleanly.""" if self._client: try: await self._client.aclose() except Exception: pass self._client = None
async def ping(self) -> dict: """Health check probe.""" if not self._url: return {"status": "unconfigured", "note": "using in-memory fallback"} if not self._client: return {"status": "down", "error": "client not connected"} started = time.perf_counter() try: res = await self._client.ping() latency = round((time.perf_counter() - started) * 1000, 1) if res: return {"status": "up", "latency_ms": latency} return {"status": "degraded", "latency_ms": latency} except Exception as e: logger.error("Redis ping failed: %s: %s", type(e).__name__, e) return {"status": "down", "error": "service unavailable"}
def _prune_memory_stores(self, now: float, max_entries: int = 5000) -> None: """Evict expired entries and bound in-memory fallback dicts to prevent unbounded growth.""" for store in (self._memory_cache, self._memory_counters): if len(store) > max_entries: expired = [k for k, (_, exp) in list(store.items()) if exp and exp <= now] for k in expired: store.pop(k, None) while len(store) > max_entries: oldest_key = min(store, key=lambda k: store[k][1] or float("inf")) store.pop(oldest_key, None)
@property def is_shared_available(self) -> bool: """Returns True if connected to an external shared Redis cluster/instance.""" return self._client is not None
async def get(self, key: str) -> Optional[str]: """Retrieve key value with in-memory fallback.""" await self._ensure_client() if self._client: try: return await self._client.get(key) except Exception as e: logger.debug(f"Redis get error: {e}") # Memory fallback item = self._memory_cache.get(key) if item: val, exp = item if exp == 0 or exp > time.time(): return val else: self._memory_cache.pop(key, None) return None
async def set(self, key: str, value: str, expire_seconds: int = 3600) -> bool: """Set key with TTL expiration.""" await self._ensure_client() if self._client: try: await self._client.set(key, value, ex=expire_seconds) return True except Exception as e: logger.debug(f"Redis set error: {e}") # Memory fallback now = time.time() exp = now + expire_seconds if expire_seconds > 0 else 0 self._prune_memory_stores(now) self._memory_cache[key] = (value, exp) return True
async def set_monotonic_corpus_revision( self, key: str, candidate: Optional[str] = None, *, seq_key: Optional[str] = None, base_prefix: str = "r1", expire_seconds: int = 2592000, ) -> str: """ Atomically issues or updates a shared corpus revision in Redis using a server-side monotonic Redis counter (`INCR`), removing worker wall-clock and container-PID dependence. - When `candidate` is None/empty, Redis atomically increments `seq_key` and sets `key` to `<base_prefix>-g<next_seq>`. - When `candidate` contains `-g<N>`, Redis never downgrades a higher stored `-g<M>`. - Never falls back silently to local memory when shared Redis is configured/connected. """ import re as _re
resolved_seq_key = seq_key or f"{key}:seq"
def _parse_gen(val: Optional[str]) -> Optional[int]: if not val: return None m = _re.match(r"^.+-g(\d+)$", str(val).strip()) return int(m.group(1)) if m else None
lua_script = """local cur = redis.call('GET', KEYS[1])local cand = ARGV[1] or ''local base = ARGV[2] or 'r1'local ttl = tonumber(ARGV[3]) or 2592000local cur_seq = tonumber(redis.call('GET', KEYS[2]) or '0') or 0if cur and cur ~= false then local g = string.match(cur, "^.+%-g(%d+)$") if g and tonumber(g) > cur_seq then cur_seq = tonumber(g) redis.call('SET', KEYS[2], tostring(cur_seq)) endendif cand == '' then local next_seq = redis.call('INCR', KEYS[2]) local new_rev = base .. '-g' .. tostring(next_seq) redis.call('SET', KEYS[1], new_rev, 'EX', ttl) return new_revendlocal n_g = string.match(cand, "^.+%-g(%d+)$")local c_g = nilif cur and cur ~= false then c_g = string.match(cur, "^.+%-g(%d+)$")endif n_g and c_g and tonumber(n_g) < tonumber(c_g) then return curendif n_g and tonumber(n_g) > cur_seq then redis.call('SET', KEYS[2], n_g)endredis.call('SET', KEYS[1], cand, 'EX', ttl)return cand""" await self._ensure_client(force_retry=True) if self._client: try: winning = await self._client.eval( lua_script, 2, key, resolved_seq_key, str(candidate or ""), base_prefix or "r1", str(expire_seconds), ) return str(winning).strip() except Exception: # Clear stale/broken client handle so future retries re-run init() cleanly failed_client = self._client self._client = None try: await failed_client.aclose() except Exception: pass raise
configured_url = os.getenv("REDIS_URL", "").strip() or self._url if configured_url: raise ConnectionError("Shared Redis client unavailable for atomic corpus revision publish.")
# Unconfigured local dev/test mode: server-like atomic counter in local memory now = time.time() existing_entry = self._memory_cache.get(key) existing_val = None if existing_entry: val, exp = existing_entry if exp == 0 or exp > now: existing_val = val seq_entry = self._memory_counters.get(resolved_seq_key) cur_seq = int(seq_entry[0]) if seq_entry else 0 cur_gen = _parse_gen(existing_val) if cur_gen is not None and cur_gen > cur_seq: cur_seq = cur_gen
if not candidate: cur_seq += 1 chosen = f"{base_prefix or 'r1'}-g{cur_seq}" else: cand_gen = _parse_gen(candidate) if cur_gen is not None and cand_gen is not None and cand_gen < cur_gen: return existing_val if cand_gen is not None and cand_gen > cur_seq: cur_seq = cand_gen chosen = str(candidate).strip()
self._memory_counters[resolved_seq_key] = (cur_seq, 0.0) exp = now + expire_seconds if expire_seconds > 0 else 0 self._prune_memory_stores(now) self._memory_cache[key] = (chosen, exp) return chosen
async def delete(self, key: str) -> bool: """Delete key.""" await self._ensure_client() if self._client: try: await self._client.delete(key) return True except Exception: pass self._memory_cache.pop(key, None) return True
async def set_nx( self, key: str, value: str, expire_seconds: int = 300, require_shared: bool = False, raise_on_error: bool = False, ) -> bool: """ Set key only if it does not already exist (distributed lock primitive). Returns True if acquired, False otherwise. If require_shared is True, fails closed when shared Redis is unavailable in production. If raise_on_error is True, re-raises transport/client exceptions instead of returning False. """ await self._ensure_client() if self._client: try: res = await self._client.set(key, value, ex=expire_seconds, nx=True) return bool(res) except Exception as e: logger.debug(f"Redis set_nx error: {e}") if raise_on_error: raise if require_shared: return False elif require_shared: from app.core.config import settings if getattr(settings, "IS_PROD", False): logger.error(f"[REDIS_FAIL_CLOSED] Cannot acquire lock '{key}' in production without shared Redis.") return False
# In-memory fallback (only for single-worker/local test environments) now = time.time() item = self._memory_cache.get(key) if item: val, exp = item if exp == 0 or exp > now: return False exp = now + expire_seconds if expire_seconds > 0 else 0 self._prune_memory_stores(now) self._memory_cache[key] = (value, exp) return True
_LUA_RELEASE_LOCK = """ if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end """
_LUA_RENEW_LOCK = """ if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return 0 end """
async def release_lock(self, key: str, owner_id: str) -> bool: """ Atomically releases lock via Lua script only if value matches owner_id. Prevents deleting a lock acquired by another worker if current worker timed out. """ if self._client: try: res = await self._client.eval(self._LUA_RELEASE_LOCK, 1, key, owner_id) return bool(res) except Exception as e: logger.debug(f"Redis Lua release_lock error: {e}") try: val = await self._client.get(key) if val == owner_id: await self._client.delete(key) return True return False except Exception: pass item = self._memory_cache.get(key) if item and item[0] == owner_id: self._memory_cache.pop(key, None) return True return False
async def renew_lock(self, key: str, owner_id: str, expire_seconds: int) -> bool: """ Atomically extends lock expiration via Lua script only if current value matches owner_id. Prevents extending a lock that was lost or expired and acquired by another worker. """ if self._client: try: res = await self._client.eval(self._LUA_RENEW_LOCK, 1, key, owner_id, expire_seconds) return bool(res) except Exception as e: logger.debug(f"Redis Lua renew_lock error: {e}") return False
# In-memory fallback item = self._memory_cache.get(key) if item and item[0] == owner_id: now = time.time() self._memory_cache[key] = (owner_id, now + expire_seconds) return True return False
async def incr(self, key: str, expire_seconds: int = 600) -> int: """Atomically increments a key with expiration, falling back to in-memory counter.""" if self._client: try: count = await self._client.incr(key) if count == 1: await self._client.expire(key, expire_seconds) return int(count) except Exception as e: logger.warning(f"Redis incr error: {e}; falling back to local tracker")
now = time.time() curr_count, exp = self._memory_counters.get(key, (0, now + expire_seconds)) if now > exp: curr_count = 0 exp = now + expire_seconds curr_count += 1 self._prune_memory_stores(now) self._memory_counters[key] = (curr_count, exp) return curr_count
async def expire(self, key: str, seconds: int) -> bool: if self._client: try: return bool(await self._client.expire(key, seconds)) except Exception: pass return True
async def check_and_increment_daily_ai_limit( self, uid: str, limit: int = 5, request_id: Optional[str] = None ) -> Tuple[bool, int]: """ Atomic daily AI query quota enforcement (P2-REDIS-01). Uses ai_quota_daily_collection in MongoDB as the single authoritative source of truth, with atomic request-bound reservation. Redis serves as an accelerator and is kept in sync. Returns: (is_allowed: bool, remaining_queries: int) """ today_str = datetime.datetime.utcnow().strftime("%Y-%m-%d") req_id = request_id or str(uuid4()) key = f"ai_quota:{uid}:{today_str}"
# 1. Authoritative check and atomic increment on ai_quota_daily_collection try: from app.infrastructure.mongodb import ai_quota_daily_collection from pymongo import ReturnDocument
res = await ai_quota_daily_collection.find_one_and_update( {"uid": uid, "day": today_str}, { "$inc": {"count": 1}, "$addToSet": {"reservations": req_id}, "$setOnInsert": {"created_at": datetime.datetime.utcnow()} }, upsert=True, return_document=ReturnDocument.AFTER ) if res and "count" in res: count = int(res["count"]) if count > limit: # Over quota: roll back the speculative reservation await ai_quota_daily_collection.update_one( {"uid": uid, "day": today_str}, { "$inc": {"count": -1}, "$pull": {"reservations": req_id} } ) # Sync to Redis if client connected if self._client: try: await self._client.set(key, str(limit), ex=90000) except Exception: pass return False, 0
remaining = max(0, limit - count) # Sync count to Redis accelerator if self._client: try: await self._client.set(key, str(count), ex=90000) except Exception: pass return True, remaining except Exception as db_err: logger.error(f"Authoritative MongoDB quota check failed: {db_err}") from app.core.config import settings if settings.IS_PROD: return False, 0 # Fail closed in production
# 2. Redis or bounded in-memory degraded fallback for non-production environments (PX-29) degraded_cap = max(1, min(limit, int(os.getenv("DEGRADED_MEMORY_QUOTA_CAP", "5")))) if self._client: try: count = await self._client.incr(key) if count == 1: await self._client.expire(key, 90000) remaining = max(0, degraded_cap - count) return count <= degraded_cap, remaining except Exception as e: logger.warning(f"Redis fallback quota error: {e}")
now = time.time() curr_count, exp = self._memory_counters.get(key, (0, now + 90000)) if now > exp: curr_count = 0 exp = now + 90000 curr_count += 1 self._memory_counters[key] = (curr_count, exp) remaining = max(0, degraded_cap - curr_count) return curr_count <= degraded_cap, remaining
async def refund_daily_ai_limit(self, uid: str, request_id: Optional[str] = None) -> None: """ Atomically refunds 1 query credit if a search request fails before completion. Uses request_id reservation if provided to guarantee idempotency and eliminate double-refund races. """ today_str = datetime.datetime.utcnow().strftime("%Y-%m-%d") key = f"ai_quota:{uid}:{today_str}"
# 1. Authoritative refund on ai_quota_daily_collection try: from app.infrastructure.mongodb import ai_quota_daily_collection from pymongo import ReturnDocument
if request_id: # Idempotent refund: only decrement if request_id is in reservations res = await ai_quota_daily_collection.find_one_and_update( {"uid": uid, "day": today_str, "reservations": request_id, "count": {"$gt": 0}}, { "$inc": {"count": -1}, "$pull": {"reservations": request_id} }, return_document=ReturnDocument.AFTER ) else: res = await ai_quota_daily_collection.find_one_and_update( {"uid": uid, "day": today_str, "count": {"$gt": 0}}, {"$inc": {"count": -1}}, return_document=ReturnDocument.AFTER )
if res and "count" in res: new_count = int(res["count"]) if self._client: try: await self._client.set(key, str(new_count), ex=90000) except Exception: pass return except Exception as db_err: logger.warning(f"Authoritative MongoDB quota refund failed: {db_err}")
# Fallback to Redis / memory in non-production if self._client: try: curr = await self._client.get(key) if curr and int(curr) > 0: await self._client.decr(key) return except Exception as e: logger.warning(f"Redis quota refund error: {e}")
if key in self._memory_counters: curr_count, exp = self._memory_counters[key] if curr_count > 0: self._memory_counters[key] = (curr_count - 1, exp)
# Global singletonredis_manager = RedisManager()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823"""Cloudflare R2 Configuration for Sahih Islam AssetsProvides secure access to private R2 bucket via signed URLs"""import osimport reimport jsonimport loggingfrom pathlib import Pathfrom typing import Optional, Dict, Any, Listimport boto3from botocore.config import Configfrom botocore.exceptions import ClientErrorimport httpx
from app.core.config import settings
logger = logging.getLogger("sahih_storage")
class DurableStorageUnavailableError(RuntimeError): """Raised when durable object storage (Cloudflare R2) fails in production/multi-worker envs."""
# R2 Bucket Configuration (Managed centrally via settings.cloudflare)R2_ACCOUNT_ID = settings.cloudflare.account_idR2_BUCKET_NAME = settings.cloudflare.r2_bucket_nameR2_ACCESS_KEY_ID = settings.cloudflare.r2_access_key_idR2_SECRET_ACCESS_KEY = settings.cloudflare.r2_secret_access_keyR2_PUBLIC_URL = settings.cloudflare.r2_public_domain
# R2 EndpointR2_ENDPOINT = f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com"
# Mapping of letter names to their R2 global numbered audio filenames# Sabaq 1 (Mufrad Huroof): Letter 1 (Alif) = 4.mp3, Letter 2 (Baa) = 5.mp3, etc.LETTER_NAME_TO_AUDIO_ID = { "alif": "4.mp3", "baa": "5.mp3", "taa": "6.mp3", "thaa": "7.mp3", "jeem": "8.mp3", "haa": "9.mp3", "khaa": "10.mp3", "daal": "11.mp3", "thaal": "12.mp3", "raa": "13.mp3", "zaa": "14.mp3", "seen": "15.mp3", "sheen": "16.mp3", "saad": "17.mp3", "daad": "18.mp3", "toot": "19.mp3", "toa": "19.mp3", "taa_heavy": "19.mp3", "zhaa": "20.mp3", "zoa": "20.mp3", "zaa_heavy": "20.mp3", "ayn": "21.mp3", "ghayn": "22.mp3", "faa": "23.mp3", "qaaf": "24.mp3", "kaaf": "25.mp3", "laam": "26.mp3", "meem": "27.mp3", "noon": "28.mp3", "waw": "29.mp3", "haa_round": "30.mp3", "hamzah": "31.mp3", "yaa": "32.mp3", "yaa_small": "33.mp3",}
# Initialize S3 client for R2 (R2 is S3-compatible)def get_r2_client(): """Get boto3 S3 client configured for Cloudflare R2, or None if credentials missing""" if not R2_ACCESS_KEY_ID or not R2_SECRET_ACCESS_KEY: return None try: return boto3.client( 's3', endpoint_url=R2_ENDPOINT, aws_access_key_id=R2_ACCESS_KEY_ID, aws_secret_access_key=R2_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4'), region_name='auto' # R2 uses 'auto' as region ) except Exception as e: print(f"Error initializing R2 S3 client: {e}") return None
# Asset FoldersR2_QURAN_TAFSEER_FOLDER = "quran_tafseer"R2_QURAN_TRANSLATION_FOLDER = "quran_translation"R2_QAIDA_AUDIO_FOLDER = "qaida_audio"R2_NIMAZ_AUDIO_FOLDER = "Nimaz_Mutarjam_audio"
from urllib.parse import quote
CF_WORKER_URL = (settings.cloudflare.worker_url or os.getenv("CF_WORKER_URL", "https://api-proxy.sahihislamapp.workers.dev")).rstrip("/")CF_MEDIA_URL = (getattr(settings.cloudflare, "media_url", "") or os.getenv("CF_MEDIA_URL") or CF_WORKER_URL).rstrip("/")
def get_media_base_url() -> str: """Resolve active Cloudflare CDN / Worker media base URL (custom domain when configured).""" env_media = (os.getenv("CLOUDFLARE_MEDIA_URL") or os.getenv("CF_MEDIA_URL") or "").strip().rstrip("/") if env_media: return env_media cfg_media = (getattr(settings.cloudflare, "media_url", "") or "").strip().rstrip("/") if cfg_media: return cfg_media env_worker = (os.getenv("CLOUDFLARE_WORKER_URL") or os.getenv("CF_WORKER_URL") or "").strip().rstrip("/") if env_worker: return env_worker return CF_MEDIA_URL or CF_WORKER_URL
# Signed URL expiration (in seconds)SIGNED_URL_EXPIRATION = 900 # 15 minutes default for least-privilege pre-signed access
ALLOWED_R2_PREFIXES = ( "quran_tafseer/", "quran_translation/", "qaida_audio/", "Nimaz_Mutarjam_audio/", "translation_audio/", "Qtranslation_mp3/", "user_uploads/", "ad_creatives/", "shop_assets/", "hadith_collections/", "r2/hadith_collections/",)
def generate_signed_url(object_key: str, expiration: int = SIGNED_URL_EXPIRATION) -> str: """ Generate a temporary signed URL for accessing a private R2 object, or falls back to public/direct URL if S3 credentials not configured. Enforces path traversal protection, key canonicalization, and expiry bounds. """ if not object_key or not isinstance(object_key, str): raise ValueError("Invalid object_key")
from urllib.parse import unquote decoded_key = object_key for _ in range(2): nxt = unquote(decoded_key) if nxt == decoded_key: break decoded_key = nxt
clean_key = decoded_key.replace("\\", "/").lstrip("/") if not clean_key or ".." in clean_key or "\x00" in clean_key: raise ValueError("Path traversal sequence detected in object key")
if not any(clean_key.startswith(pfx) for pfx in ALLOWED_R2_PREFIXES): raise ValueError(f"Unauthorized object key prefix: '{clean_key}'")
object_key = clean_key # Clamp expiration to [60, 3600] seconds (max 1 hour) expiration = max(60, min(int(expiration), 3600)) s3_client = get_r2_client() if s3_client: try: return s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': R2_BUCKET_NAME, 'Key': object_key }, ExpiresIn=expiration ) except ClientError as e: raise RuntimeError(f"Failed to generate signed URL for private object '{object_key}': {e}") # Fail closed: never leak direct public URL on private signed URL request (P2-STO-01) raise RuntimeError(f"Failed to generate signed URL for private object '{object_key}': R2 credentials not configured")
def get_tafseer_url(filename: str, signed: bool = False) -> str: """ Get Cloudflare CDN / Worker URL for a Quran Tafseer JSON file (e.g. Al_Fatihah_Tafseer.json). Uses CF_MEDIA_URL / CF_WORKER_URL by default so Cloudflare caches globally instead of bypassing CDN via raw S3 URLs. """ object_key = f"{R2_QURAN_TAFSEER_FOLDER}/{filename}" if signed: return generate_signed_url(object_key) base_url = get_media_base_url() if base_url: for num, fn in SURAH_NAMES.items(): if fn == filename: return f"{base_url}/api/r2/tafseer/{num}" return f"{base_url}/api/r2/object/{quote(object_key, safe='/')}" if R2_PUBLIC_URL: return f"{R2_PUBLIC_URL}/{object_key}" return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
def get_translation_url(filename: str, signed: bool = False) -> str: """ Get Cloudflare CDN / Worker URL for a Quran Translation JSON file (e.g. Al_Fatihah_Translation.json) for sub-15ms edge caching. """ object_key = f"{R2_QURAN_TRANSLATION_FOLDER}/{filename}" if signed: return generate_signed_url(object_key) base_url = get_media_base_url() if base_url: for num, fn in SURAH_NAMES.items(): if fn.replace("_Tafseer.json", "_Translation.json") == filename: return f"{base_url}/api/r2/translation/{num}" return f"{base_url}/api/r2/object/{quote(object_key, safe='/')}" if R2_PUBLIC_URL: return f"{R2_PUBLIC_URL}/{object_key}" return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
def resolve_qaida_filename(filename: str) -> str: """ Normalize filename to match R2 bucket layout: - Preserves sabaq-scoped folders (sabaq 1/..sabaq 17/) completely independent - Strips 'numbered/' or 'qaida_audio/' prefixes for legacy flat paths - Resolves letter names (e.g., 'alif.mp3' -> '4.mp3', 'baa.mp3' -> '5.mp3') """ clean_name = filename.strip("/").replace("\\", "/") if clean_name.startswith("qaida_audio/"): clean_name = clean_name[len("qaida_audio/"):]
if re.match(r"^(?:[^/]+/)?sabaq\s+\d+/", clean_name, re.IGNORECASE): return clean_name
if clean_name.startswith("numbered/"): clean_name = clean_name[len("numbered/"):] # Check letter name mapping name_no_ext = clean_name.rsplit(".", 1)[0].lower() if name_no_ext in LETTER_NAME_TO_AUDIO_ID: return LETTER_NAME_TO_AUDIO_ID[name_no_ext] return clean_name
def get_qaida_audio_url(filename: str, signed: bool = False) -> str: """ Get Cloudflare CDN / Worker URL for a Qaida audio file (`/api/r2/qaida/audio/{resolved_filename}`). """ resolved_file = resolve_qaida_filename(filename) object_key = f"{R2_QAIDA_AUDIO_FOLDER}/{resolved_file}" if signed: return generate_signed_url(object_key) base_url = get_media_base_url() if base_url: return f"{base_url}/api/r2/qaida/audio/{quote(resolved_file, safe='/')}" if R2_PUBLIC_URL: return f"{R2_PUBLIC_URL}/{object_key}" return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
def resolve_nimaz_filename(filename: str) -> str: """ Normalize filename for Nimaz Mutarjam audio in R2: - Strips 'Nimaz_Mutarjam_audio/' or 'nimaz/' prefix - Ensures clean path for R2 key """ clean_name = filename.strip("/").replace("\\", "/") if clean_name.startswith("Nimaz_Mutarjam_audio/"): clean_name = clean_name[len("Nimaz_Mutarjam_audio/"):] if clean_name.startswith("nimaz/"): clean_name = clean_name[len("nimaz/"):] return clean_name
def get_nimaz_audio_url(filename: str, signed: bool = False) -> str: """ Get Cloudflare CDN / Worker URL for a Nimaz Mutarjam audio file (`/api/r2/nimaz/audio/{clean_name}`). """ clean_name = resolve_nimaz_filename(filename) object_key = f"{R2_NIMAZ_AUDIO_FOLDER}/{clean_name}" if signed: return generate_signed_url(object_key) base_url = get_media_base_url() if base_url: return f"{base_url}/api/r2/nimaz/audio/{quote(clean_name, safe='/')}" if R2_PUBLIC_URL: return f"{R2_PUBLIC_URL}/{object_key}" return f"{R2_ENDPOINT}/{R2_BUCKET_NAME}/{object_key}"
def get_tafseer_by_surah(surah_number: int, signed: bool = False) -> str: """ Get Cloudflare CDN / Worker URL for Tafseer by Surah number (1-114). """ filename = SURAH_NAMES.get(surah_number) if not filename: raise ValueError(f"Invalid Surah number (1-114): {surah_number}") return get_tafseer_url(filename, signed=signed)
# Surah name mappings for tafseer filesSURAH_NAMES = { 1: "Al_Fatihah_Tafseer.json", 2: "Al_Baqarah_Tafseer.json", 3: "Aal_Imran_Tafseer.json", 4: "An_Nisa_Tafseer.json", 5: "Al_Maidah_Tafseer.json", 6: "Al_Anam_Tafseer.json", 7: "Al_Araf_Tafseer.json", 8: "Al_Anfal_Tafseer.json", 9: "At_Tawbah_Tafseer.json", 10: "Yunus_Tafseer.json", 11: "Hud_Tafseer.json", 12: "Yusuf_Tafseer.json", 13: "Ar_Rad_Tafseer.json", 14: "Ibrahim_Tafseer.json", 15: "Al_Hijr_Tafseer.json", 16: "An_Nahl_Tafseer.json", 17: "Al_Isra_Tafseer.json", 18: "Al_Kahf_Tafseer.json", 19: "Maryam_Tafseer.json", 20: "Ta_Ha_Tafseer.json", 21: "Al_Anbiya_Tafseer.json", 22: "Al_Hajj_Tafseer.json", 23: "Al_Muminun_Tafseer.json", 24: "An_Nur_Tafseer.json", 25: "Al_Furqan_Tafseer.json", 26: "Ash_Shuara_Tafseer.json", 27: "An_Naml_Tafseer.json", 28: "Al_Qasas_Tafseer.json", 29: "Al_Ankabut_Tafseer.json", 30: "Ar_Rum_Tafseer.json", 31: "Luqman_Tafseer.json", 32: "As_Sajdah_Tafseer.json", 33: "Al_Ahzab_Tafseer.json", 34: "Saba_Tafseer.json", 35: "Fatir_Tafseer.json", 36: "Ya_Sin_Tafseer.json", 37: "As_Saffat_Tafseer.json", 38: "Sad_Tafseer.json", 39: "Az_Zumar_Tafseer.json", 40: "Ghafir_Tafseer.json", 41: "Fussilat_Tafseer.json", 42: "Ash_Shura_Tafseer.json", 43: "Az_Zukhruf_Tafseer.json", 44: "Ad_Dukhan_Tafseer.json", 45: "Al_Jathiyah_Tafseer.json", 46: "Al_Ahqaf_Tafseer.json", 47: "Muhammad_Tafseer.json", 48: "Al_Fath_Tafseer.json", 49: "Al_Hujurat_Tafseer.json", 50: "Qaf_Tafseer.json", 51: "Adh_Dhariyat_Tafseer.json", 52: "At_Tur_Tafseer.json", 53: "An_Najm_Tafseer.json", 54: "Al_Qamar_Tafseer.json", 55: "Ar_Rahman_Tafseer.json", 56: "Al_Waqiah_Tafseer.json", 57: "Al_Hadid_Tafseer.json", 58: "Al_Mujadilah_Tafseer.json", 59: "Al_Hashr_Tafseer.json", 60: "Al_Mumtahanah_Tafseer.json", 61: "As_Saff_Tafseer.json", 62: "Al_Jumuah_Tafseer.json", 63: "Al_Munafiqun_Tafseer.json", 64: "At_Taghabun_Tafseer.json", 65: "At_Talaq_Tafseer.json", 66: "At_Tahrim_Tafseer.json", 67: "Al_Mulk_Tafseer.json", 68: "Al_Qalam_Tafseer.json", 69: "Al_Haqqah_Tafseer.json", 70: "Al_Maarij_Tafseer.json", 71: "Nuh_Tafseer.json", 72: "Al_Jinn_Tafseer.json", 73: "Al_Muzzammil_Tafseer.json", 74: "Al_Muddaththir_Tafseer.json", 75: "Al_Qiyamah_Tafseer.json", 76: "Al_Insan_Tafseer.json", 77: "Al_Mursalat_Tafseer.json", 78: "An_Naba_Tafseer.json", 79: "An_Naziat_Tafseer.json", 80: "Abasa_Tafseer.json", 81: "At_Takwir_Tafseer.json", 82: "Al_Infitar_Tafseer.json", 83: "Al_Mutaffifin_Tafseer.json", 84: "Al_Inshiqaq_Tafseer.json", 85: "Al_Buruj_Tafseer.json", 86: "At_Tariq_Tafseer.json", 87: "Al_Ala_Tafseer.json", 88: "Al_Ghashiyah_Tafseer.json", 89: "Al_Fajr_Tafseer.json", 90: "Al_Balad_Tafseer.json", 91: "Ash_Shams_Tafseer.json", 92: "Al_Lail_Tafseer.json", 93: "Ad_Duha_Tafseer.json", 94: "Ash_Sharh_Tafseer.json", 95: "At_Tin_Tafseer.json", 96: "Al_Alaq_Tafseer.json", 97: "Al_Qadr_Tafseer.json", 98: "Al_Bayyinah_Tafseer.json", 99: "Az_Zalzalah_Tafseer.json", 100: "Al_Adiyat_Tafseer.json", 101: "Al_Qariah_Tafseer.json", 102: "At_Takathur_Tafseer.json", 103: "Al_Asr_Tafseer.json", 104: "Al_Humazah_Tafseer.json", 105: "Al_Fil_Tafseer.json", 106: "Quraish_Tafseer.json", 107: "Al_Maun_Tafseer.json", 108: "Al_Kauthar_Tafseer.json", 109: "Al_Kafirun_Tafseer.json", 110: "An_Nasr_Tafseer.json", 111: "Al_Masad_Tafseer.json", 112: "Al_Ikhlas_Tafseer.json", 113: "Al_Falaq_Tafseer.json", 114: "An_Nas_Tafseer.json",}
def get_tafseer_by_name(surah_number: int, signed: bool = False) -> Optional[str]: """Get Cloudflare CDN / Worker URL for Tafseer by Surah number using actual file names""" filename = SURAH_NAMES.get(surah_number) if filename: return get_tafseer_url(filename, signed=signed) return None
SURAH_TRANSLATION_NAMES: Dict[int, str] = { num: name.replace("_Tafseer.json", "_Translation.json") for num, name in SURAH_NAMES.items()}
def get_translation_by_name(surah_number: int, signed: bool = False) -> Optional[str]: """Get Cloudflare CDN / Worker URL for Translation by Surah number using actual file names""" filename = SURAH_TRANSLATION_NAMES.get(surah_number) if filename: return get_translation_url(filename, signed=signed) return None
_TRANSLATION_CACHE: Dict[int, Dict[str, Any]] = {}_TRANSLATION_CACHE_REVISION: Optional[str] = None_TRANSLATION_CACHE_HOOK_REGISTERED: bool = False
def _clear_translation_cache() -> None: global _TRANSLATION_CACHE_REVISION _TRANSLATION_CACHE.clear() try: from app.rag.cache import get_corpus_revision _TRANSLATION_CACHE_REVISION = get_corpus_revision() except Exception: _TRANSLATION_CACHE_REVISION = None
def _ensure_translation_cache_revision_synced() -> None: global _TRANSLATION_CACHE_REVISION, _TRANSLATION_CACHE_HOOK_REGISTERED try: from app.rag.cache import get_corpus_revision, register_cache_clear_hook if not _TRANSLATION_CACHE_HOOK_REGISTERED: register_cache_clear_hook(_clear_translation_cache) _TRANSLATION_CACHE_HOOK_REGISTERED = True active_rev = get_corpus_revision() if _TRANSLATION_CACHE_REVISION != active_rev: _TRANSLATION_CACHE.clear() _TRANSLATION_CACHE_REVISION = active_rev except Exception: pass
def _normalize_surah_payload(raw_json: Dict[str, Any], surah_no: int) -> Dict[str, Any]: """ Normalizes the Quran translation payload so that: 1. It matches the frontend expectation at /auth/quran/surah/{surah_no} 2. ayahs[i]['translations'] is a dictionary mapping { 'en.sahih': '...', 'ur.jalandhry': '...' } 3. It also includes translations_map and translations_list for versatile consumer access. """ surah_meta = raw_json.get("surah", {}) name_ar = surah_meta.get("name_arabic") or raw_json.get("name_arabic", "") name_en = surah_meta.get("name_english") or raw_json.get("name_english", "") total_ayahs = surah_meta.get("total_ayahs") or raw_json.get("total_ayahs", 0) rev_type = surah_meta.get("revelation_type") or raw_json.get("revelation_type", "Meccan") trans_en = surah_meta.get("translation_english") or raw_json.get("translation_english", "") available_trans = raw_json.get("available_translations", [])
raw_ayahs = raw_json.get("ayahs", []) if not raw_ayahs and "surahs" in raw_json and raw_json["surahs"]: raw_ayahs = raw_json["surahs"][0].get("ayahs", [])
normalized_ayahs = [] for idx, a in enumerate(raw_ayahs): ayah_no = a.get("ayah_no", idx + 1) text_ar = a.get("text_arabic", "") # Build dictionary of translations t_map: Dict[str, str] = {} if isinstance(a.get("translations_map"), dict): t_map = dict(a["translations_map"]) elif isinstance(a.get("translations"), dict): t_map = dict(a["translations"]) elif isinstance(a.get("translations"), list): for item in a["translations"]: if isinstance(item, dict) and "translation_id" in item: t_map[item["translation_id"]] = item.get("text", "")
t_list = a.get("translations") if isinstance(a.get("translations"), list) else [ {"translation_id": k, "text": v} for k, v in t_map.items() ]
normalized_ayahs.append({ "ayah_no": ayah_no, "reference": a.get("reference", f"{surah_no}:{ayah_no}"), "text_arabic": text_ar, "translations": t_map, # Direct dictionary for Dart frontend: translations[_selectedTranslationId] "translations_map": t_map, "translations_list": t_list, })
return { "surah_no": surah_no, "name_arabic": name_ar, "name_english": name_en, "translation_english": trans_en, "total_ayahs": total_ayahs if total_ayahs else len(normalized_ayahs), "revelation_type": rev_type, "available_translations": available_trans, "ayahs": normalized_ayahs, }
class TranslationSourceError(RuntimeError): """Raised when both/fallback Quran translation sources fail rather than cleanly reporting missing."""
async def fetch_translation_data(surah_number: int, raise_on_error: bool = False) -> Optional[Dict[str, Any]]: """ Fetch Quran Translation for a Surah with resilient tiered fallback: Tier 1: Revision-aware In-Memory Cache (0.1ms) Tier 2: MongoDB Primary Database fallback (2ms) Tier 4: Cloudflare Edge Worker / R2 Bucket (<30ms)
When raise_on_error=True, transport/server errors on MongoDB or R2 raise TranslationSourceError instead of collapsing to None ("not found"). """ try: from app.rag.cache import refresh_corpus_revision await refresh_corpus_revision() except Exception: pass _ensure_translation_cache_revision_synced()
if surah_number in _TRANSLATION_CACHE: return _TRANSLATION_CACHE[surah_number]
filename = SURAH_TRANSLATION_NAMES.get(surah_number) if not filename: return None
mongo_error: Optional[Exception] = None r2_error: Optional[Exception] = None
# Tier 2: MongoDB Primary Database fallback (Instant 2ms) try: from .mongodb import quran_collection db_doc = await quran_collection.find_one({"surah_no": surah_number}, {"_id": 0}) if db_doc: normalized = _normalize_surah_payload(db_doc, surah_number) first_ayah_trans = normalized.get("ayahs", [{}])[0].get("translations", {}) if "ur.roman" in first_ayah_trans and "ks.kashmiri" in first_ayah_trans: _TRANSLATION_CACHE[surah_number] = normalized return normalized except Exception as dbe: mongo_error = dbe print(f"⚠️ [Mongo Translation Fallback] Error for Surah {surah_number}: {dbe}")
# Tier 4: Cloudflare Edge Worker / R2 (External network fallback, short timeout) cf_url = f"{get_media_base_url()}/api/r2/translation/{surah_number}" try: headers = {} try: from app.core.media_token import issue_media_jwt headers["Authorization"] = f"Bearer {issue_media_jwt('backend:origin', 'service', 300)['token']}" except Exception: pass async with httpx.AsyncClient(timeout=2.0, follow_redirects=True) as client: resp = await client.get(cf_url, headers=headers) if resp.status_code in (200, 206): raw_json = resp.json() normalized = _normalize_surah_payload(raw_json, surah_number) _TRANSLATION_CACHE[surah_number] = normalized return normalized if resp.status_code != 404: r2_error = RuntimeError(f"R2 HTTP {resp.status_code} for Surah {surah_number}") except Exception as e: r2_error = e print(f"⚠️ [CF R2 Translation] Network fetch failed for Surah {surah_number}: {e}")
if raise_on_error and (r2_error is not None or mongo_error is not None): raise TranslationSourceError( f"Failed to fetch Surah {surah_number} translation data (mongo_error={mongo_error!r}, r2_error={r2_error!r})" )
return None
def list_r2_objects(prefix: str = "", max_keys: int = 1000) -> list: """ List objects in R2 bucket with given prefix Args: prefix: Object key prefix to filter (e.g., "quran_tafseer/") max_keys: Maximum number of objects to return Returns: List of object metadata dictionaries """ try: s3_client = get_r2_client() if not s3_client: return [] response = s3_client.list_objects_v2( Bucket=R2_BUCKET_NAME, Prefix=prefix, MaxKeys=max_keys ) if 'Contents' not in response: return [] return [ { 'key': obj['Key'], 'size': obj['Size'], 'last_modified': obj['LastModified'].isoformat(), 'etag': obj['ETag'].strip('"') } for obj in response['Contents'] ] except ClientError as e: raise Exception(f"Failed to list R2 objects: {e}")
def extract_r2_key_from_url(ref: Any) -> Optional[str]: """Extract an R2 object key from a URL, r2:// URI, or direct R2 path.""" if not isinstance(ref, str): return None raw = ref.strip() if not raw or raw.startswith("data:"): return None if raw.startswith("r2://"): key = raw[5:].lstrip("/") return key or None if "/api/r2/image/" in raw: subpath = raw.split("/api/r2/image/", 1)[1].split("?", 1)[0].lstrip("/") return f"images/{subpath}" if subpath else None if "/api/r2/media" in raw and "key=" in raw: from urllib.parse import parse_qs, urlsplit qs = parse_qs(urlsplit(raw).query) vals = qs.get("key") or [] return vals[0].lstrip("/") if vals and vals[0] else None if raw.startswith(("images/", "uploads/", "avatars/", "shops/", "products/", "ads/", "proofs/")): return raw.split("?", 1)[0].lstrip("/") return None
async def delete_r2_objects(refs: List[Any]) -> Dict[str, Any]: """Delete deduplicated R2 objects safely via asyncio.to_thread when R2 client is configured.""" import asyncio
keys = sorted({k for k in (extract_r2_key_from_url(r) for r in refs) if k}) if not keys: return {"deleted": [], "failed": [], "skipped_unconfigured": False}
s3 = get_r2_client() if not s3: return {"deleted": [], "failed": [], "skipped_unconfigured": True, "keys": keys}
deleted: List[str] = [] failed: List[str] = []
def _delete_one(obj_key: str) -> None: s3.delete_object(Bucket=R2_BUCKET_NAME, Key=obj_key)
for key in keys: try: await asyncio.to_thread(_delete_one, key) deleted.append(key) except Exception as exc: err_str = str(exc).lower() if "nosuchkey" in err_str or "404" in err_str or "not found" in err_str: deleted.append(key) else: failed.append(f"{key}: {exc}")
return {"deleted": deleted, "failed": failed, "skipped_unconfigured": False}
# ============================================================================# CLOUDFLARE R2 & EDGE IMAGE PIPELINE# ============================================================================
UPLOAD_STATIC_DIR = Path(__file__).parent.parent.parent / "static" / "uploads"UPLOAD_STATIC_DIR.mkdir(parents=True, exist_ok=True)
async def upload_image_file( image_bytes: bytes, filename: str, content_type: str = "image/jpeg", category: str = "general", require_durable: Optional[bool] = None,) -> Dict[str, Any]: """ Enterprise High-Performance Image Uploader for Sahih Islam: 1. Sanitizes filename, generates immutable UUID-stamped filename. 2. Primary: Uploads to Cloudflare Edge / R2 Bucket (Zero egress, global sub-15ms CDN). 3. Secondary: Boto3 S3 R2 Client upload if credentials available. 4. Local fallback is ONLY allowed in single-worker local dev; production, staging, container, and multi-worker deployments fail closed (DurableStorageUnavailableError) when durable R2 storage cannot persist the asset. """ import uuid import re import asyncio
clean_category = re.sub(r"[^a-zA-Z0-9_\-]", "", category) or "general" ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "jpg" if ext not in ["jpg", "jpeg", "png", "webp"]: ext = "jpg" unique_name = f"{uuid.uuid4().hex[:16]}.{ext}" subpath = f"{clean_category}/{unique_name}" size_kb = round(len(image_bytes) / 1024, 2)
is_multi_worker_or_container = bool( getattr(settings, "IS_PROD", False) or getattr(settings, "IS_STAGING", False) or int(os.getenv("WEB_WORKERS", "1") or "1") > 1 or os.getenv("SPACE_ID") or os.getenv("K_SERVICE") ) durable_required = is_multi_worker_or_container if require_durable is None else bool(require_durable)
# Tier 1: Cloudflare Edge Worker Direct R2 Upload cf_endpoint = f"{CF_WORKER_URL}/api/r2/image/{subpath}" upload_secret = settings.cloudflare.worker_secret cf_err_msg = "" try: async with httpx.AsyncClient(timeout=8.0) as client: resp = await client.put( cf_endpoint, content=image_bytes, headers={ "Content-Type": content_type, "X-Upload-Key": upload_secret, } ) if resp.status_code in (200, 201): data = resp.json() public_url = data.get("url") or f"{CF_WORKER_URL}/api/r2/image/{subpath}" return { "image_url": public_url, "key": f"images/{subpath}", "size_kb": size_kb, "provider": "cloudflare_edge" } cf_err_msg = f"HTTP {resp.status_code}" except Exception as cf_err: cf_err_msg = str(cf_err)
# Tier 2: Direct Boto3 R2 S3 Upload s3_client = get_r2_client() s3_err_msg = "" if s3_client: r2_key = f"images/{subpath}" try: await asyncio.to_thread( s3_client.put_object, Bucket=R2_BUCKET_NAME, Key=r2_key, Body=image_bytes, ContentType=content_type, CacheControl="public, max-age=31536000, immutable" ) public_url = f"{CF_WORKER_URL}/api/r2/image/{subpath}" return { "image_url": public_url, "key": r2_key, "size_kb": size_kb, "provider": "r2_s3" } except Exception as s3_err: s3_err_msg = str(s3_err) else: s3_err_msg = "R2 client unconfigured"
if durable_required: logger.error( "upload_image_file: durable R2 upload failed (cf=%s, s3=%s); refusing ephemeral local fallback", cf_err_msg or "failed", s3_err_msg or "failed", ) raise DurableStorageUnavailableError( "Durable object storage upload failed; cannot store uploaded image on ephemeral container disk." )
# Tier 3: Local Persistent CDN Storage (single-worker local development only) target_dir = UPLOAD_STATIC_DIR / clean_category target_dir.mkdir(parents=True, exist_ok=True) file_path = target_dir / unique_name def _write_file(): with open(file_path, "wb") as f: f.write(image_bytes) await asyncio.to_thread(_write_file) local_url = f"/static/uploads/{clean_category}/{unique_name}" return { "image_url": local_url, "key": f"static/uploads/{clean_category}/{unique_name}", "size_kb": size_kb, "provider": "local_cdn" }
123456789"""Backward-compatible proxy for core.rate_limits"""from app.core.rate_limits import limiter, enterprise_key_func
# Alias for legacy internal references_enterprise_key_func = enterprise_key_func
__all__ = ["limiter", "enterprise_key_func", "_enterprise_key_func"]1234567"""Application Factory & ASGI EntrypointExposes create_app and the root FastAPI app instance according to the modular monolith pattern."""from run import create_app, app
__all__ = ["create_app", "app"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951# =========================================================# PYDANTIC MODELS - AADS & MARKETPLACE SYSTEM# =========================================================# Complete data models for advertisements, products, and orders# =========================================================
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validatorfrom typing import Optional, List, Dict, Anyfrom datetime import datetimefrom enum import Enumimport re
# =========================================================# ENUMS - Status Types# =========================================================
class AdStatus(str, Enum): """Ad campaign status workflow""" DRAFT = "draft" # Created but not submitted PENDING = "pending" # Awaiting admin approval ACTIVE = "active" # Approved and running PAUSED = "paused" # Temporarily stopped by advertiser REJECTED = "rejected" # Rejected by admin COMPLETED = "completed" # End date reached CANCELLED = "cancelled" # Cancelled by advertiser
class ProductStatus(str, Enum): """Product listing status""" DRAFT = "draft" ACTIVE = "active" OUT_OF_STOCK = "out_of_stock" INACTIVE = "inactive"
class OrderStatus(str, Enum): """Order fulfillment workflow""" PENDING = "pending" CONFIRMED = "confirmed" PROCESSING = "processing" SHIPPED = "shipped" DELIVERED = "delivered" CANCELLED = "cancelled" REFUNDED = "refunded"
class AdCategory(str, Enum): """Advertisement categories""" ISLAMIC_BOOKS = "Islamic Books & Quran" ATTAR_PERFUMES = "Attar, Oudh & Perfumes" ABAYAS_WEAR = "Abayas & Modest Wear" PRAYER_MATS = "Prayer Mats & Tasbih" HALAL_FOODS = "Halal Foods & Honey" DATES_DRY_FRUITS = "Dates & Dry Fruits" ISLAMIC_ART = "Islamic Art & Home Decor" HIJABS_SCARVES = "Hijabs & Scarves" THOBES_KURTAS = "Thobes & Kurtas" HALAL_COSMETICS = "Halal Cosmetics & Health" HAJJ_UMRAH = "Hajj & Umrah Essentials" ISLAMIC_ELECTRONICS = "Islamic Electronics & Clocks" KIDS_TOYS = "Kids Islamic Toys & Books" HALAL_MEAT = "Halal Meat & Groceries" CAPS_TURBANS = "Keffiyeh, Caps & Turbans" ISLAMIC_JEWELRY = "Islamic Jewelry & Rings" ISLAMIC_GIFTS = "Islamic Gifts & Hampers" HERBAL_MEDICINE = "Herbal Medicine & Tibb-e-Nabawi" CHARITY_SADAQAH = "Charity & Sadaqah Jariyah" ISLAMIC_COURSES = "Islamic Courses & Services" OTHER_HALAL = "Other Halal Products" # Legacy categories BOOKS = "Books" EDUCATION = "Education" DECOR = "Decor" FINANCE = "Finance" PRODUCTS = "Products" SERVICES = "Services" CHARITY = "Charity" EVENTS = "Events" PRAYER_ESSENTIALS = "Prayer Essentials" ISLAMIC_CLOTHING = "Islamic Clothing" HOME_DECOR = "Home Decor" JEWELRY = "Jewelry" ACCESSORIES = "Accessories" GIFTS = "Gifts" DIGITAL_PRODUCTS = "Digital Products"
class ProductCategory(str, Enum): """Product categories""" ISLAMIC_BOOKS = "Islamic Books & Quran" ATTAR_PERFUMES = "Attar, Oudh & Perfumes" ABAYAS_WEAR = "Abayas & Modest Wear" PRAYER_MATS = "Prayer Mats & Tasbih" HALAL_FOODS = "Halal Foods & Honey" DATES_DRY_FRUITS = "Dates & Dry Fruits" ISLAMIC_ART = "Islamic Art & Home Decor" HIJABS_SCARVES = "Hijabs & Scarves" THOBES_KURTAS = "Thobes & Kurtas" HALAL_COSMETICS = "Halal Cosmetics & Health" HAJJ_UMRAH = "Hajj & Umrah Essentials" ISLAMIC_ELECTRONICS = "Islamic Electronics & Clocks" KIDS_TOYS = "Kids Islamic Toys & Books" HALAL_MEAT = "Halal Meat & Groceries" CAPS_TURBANS = "Keffiyeh, Caps & Turbans" ISLAMIC_JEWELRY = "Islamic Jewelry & Rings" ISLAMIC_GIFTS = "Islamic Gifts & Hampers" HERBAL_MEDICINE = "Herbal Medicine & Tibb-e-Nabawi" CHARITY_SADAQAH = "Charity & Sadaqah Jariyah" ISLAMIC_COURSES = "Islamic Courses & Services" OTHER_HALAL = "Other Halal Products" # Legacy categories BOOKS = "Books" PRAYER_ESSENTIALS = "Prayer Essentials" ISLAMIC_CLOTHING = "Islamic Clothing" HOME_DECOR = "Home Decor" JEWELRY = "Jewelry" ACCESSORIES = "Accessories" GIFTS = "Gifts" DIGITAL_PRODUCTS = "Digital Products" EDUCATION = "Education" DECOR = "Decor" FINANCE = "Finance" PRODUCTS = "Products" SERVICES = "Services" CHARITY = "Charity" EVENTS = "Events"
# =========================================================# AD CAMPAIGN MODELS# =========================================================
class AdCreate(BaseModel): """Model for creating a new ad campaign""" title: str = Field(..., min_length=3, max_length=100) description: str = Field(..., min_length=3, max_length=1000) image_url: str = Field(..., description="URL to ad banner image") destination_url: str = Field(..., description="Landing page URL") category: str = Field(..., min_length=2, max_length=100) budget: float = Field(0.0, ge=0, description="Total budget (0 = Free)") daily_budget: Optional[float] = Field(None, ge=0, description="Daily spending limit") start_date: datetime end_date: datetime targeting: Optional[dict] = Field(default_factory=dict, description="Geographic/demographic targeting") cta_text: Optional[str] = Field("Shop Now", description="Call to action button label") @field_validator('end_date') @classmethod def validate_dates(cls, v, info): if 'start_date' in info.data and v <= info.data['start_date']: raise ValueError('end_date must be after start_date') return v
class AdUpdate(BaseModel): """Model for updating an existing ad campaign""" title: Optional[str] = Field(None, min_length=3, max_length=100) description: Optional[str] = Field(None, min_length=3, max_length=1000) image_url: Optional[str] = None destination_url: Optional[str] = None category: Optional[str] = None budget: Optional[float] = Field(None, gt=0) daily_budget: Optional[float] = Field(None, gt=0) start_date: Optional[datetime] = None end_date: Optional[datetime] = None targeting: Optional[dict] = None cta_text: Optional[str] = Field(None, description="Call to action button label")
class AdResponse(BaseModel): """Complete ad campaign response""" id: str = Field(..., alias="_id", description="MongoDB document ID") ad_id: str advertiser_uid: str advertiser_email: Optional[str] = None title: str description: str image_url: str destination_url: str category: str status: AdStatus budget: float daily_budget: Optional[float] = None cta_text: Optional[str] = "Shop Now" spent: float = 0.0 impressions: int = 0 clicks: int = 0 conversions: int = 0 start_date: datetime end_date: datetime targeting: dict = Field(default_factory=dict) created_at: datetime updated_at: datetime submitted_at: Optional[datetime] = None approved_at: Optional[datetime] = None rejected_at: Optional[datetime] = None rejection_reason: Optional[str] = None
model_config = ConfigDict(populate_by_name=True)
# =========================================================# PRODUCT MODELS# =========================================================
class ProductVariant(BaseModel): """Product variant (size, color, etc.)""" variant_id: str name: str # e.g., "Large", "Blue", "Hardcover" price_adjustment: float = 0.0 # Price difference from base stock: int = 0 sku: Optional[str] = None
class ProductCreate(BaseModel): """Model for creating a new product""" title: str = Field(..., min_length=3, max_length=200) description: str = Field(..., min_length=3, max_length=5000) price: float = Field(..., gt=0) compare_at_price: Optional[float] = Field(None, gt=0, description="Original price (for showing discounts)") category: str = Field(..., min_length=2, max_length=100) subcategory: Optional[str] = None tags: List[str] = Field(default_factory=list, description="Search tags") images: List[str] = Field(..., min_length=1, max_length=5, description="Product images (1 to 5 images)") stock: int = Field(..., ge=0) sku: Optional[str] = Field(None, description="Stock Keeping Unit") weight: Optional[float] = Field(None, gt=0, description="Weight in kg") dimensions: Optional[dict] = Field(None, description="Length, width, height in cm") variants: List[ProductVariant] = Field(default_factory=list) shipping_cost: float = Field(0.0, ge=0) shipping_regions: List[str] = Field(default_factory=lambda: ["Worldwide"]) is_digital: bool = False digital_file_url: Optional[str] = Field(None, description="Download URL for digital products") @field_validator('compare_at_price') @classmethod def validate_compare_price(cls, v, info): if v is not None and 'price' in info.data and v <= info.data['price']: raise ValueError('compare_at_price must be greater than price') return v
class ProductUpdate(BaseModel): """Model for updating an existing product""" title: Optional[str] = Field(None, min_length=3, max_length=200) description: Optional[str] = Field(None, min_length=3, max_length=5000) price: Optional[float] = Field(None, gt=0) compare_at_price: Optional[float] = Field(None, gt=0) category: Optional[str] = None subcategory: Optional[str] = None tags: Optional[List[str]] = None images: Optional[List[str]] = None stock: Optional[int] = Field(None, ge=0) sku: Optional[str] = None weight: Optional[float] = Field(None, gt=0) dimensions: Optional[dict] = None variants: Optional[List[ProductVariant]] = None shipping_cost: Optional[float] = Field(None, ge=0) shipping_regions: Optional[List[str]] = None is_digital: Optional[bool] = None digital_file_url: Optional[str] = None status: Optional[ProductStatus] = None
class ProductResponse(BaseModel): """Complete product response""" id: str = Field(..., alias="_id") product_id: str seller_uid: str seller_name: str seller_email: Optional[str] = None shop_name: Optional[str] = None title: str description: str price: float compare_at_price: Optional[float] = None category: str subcategory: Optional[str] = None tags: List[str] = Field(default_factory=list) images: List[str] stock: int sku: Optional[str] = None weight: Optional[float] = None dimensions: Optional[dict] = None variants: List[ProductVariant] = Field(default_factory=list) shipping_cost: float = 0.0 shipping_regions: List[str] = Field(default_factory=list) is_digital: bool = False digital_file_url: Optional[str] = None status: ProductStatus rating: float = 0.0 rating_count: int = 0 total_sales: int = 0 views: int = 0 created_at: datetime updated_at: datetime
model_config = ConfigDict(populate_by_name=True)
# =========================================================# ORDER & PAYMENT MODELS# =========================================================
class PaymentMethod(str, Enum): WALLET = "wallet" CARD = "card" UPI = "upi" COD = "cod" SANDBOX = "sandbox"
class PaymentStatus(str, Enum): PENDING = "pending" COMPLETED = "completed" FAILED = "failed" REFUNDED = "refunded"
class OrderItem(BaseModel): """Single item in an order""" product_id: str product_title: Optional[str] = "Product" variant_id: Optional[str] = None variant_name: Optional[str] = None quantity: int = Field(default=1, gt=0) unit_price: Optional[float] = 0.0 total_price: Optional[float] = 0.0 seller_uid: Optional[str] = ""
class ShippingAddress(BaseModel): """Shipping address information""" full_name: str = "Customer" phone: str = "" address_line1: str = "Address" address_line2: Optional[str] = None city: str = "City" state: Optional[str] = None postal_code: str = "000000" country: str = "India"
class OrderCreate(BaseModel): """Model for creating a new order""" items: List[OrderItem] = Field(..., min_length=1) shipping_address: Optional[ShippingAddress] = Field(default_factory=ShippingAddress) billing_address: Optional[ShippingAddress] = None payment_method: str = "online" notes: Optional[str] = None idempotency_key: Optional[str] = Field(None, max_length=128)
class WalletTopUpRequest(BaseModel): """Model for topping up ad/user wallet""" amount: float = Field(..., gt=0, description="Amount in currency units (INR/USD)") target_user_id: Optional[str] = Field(None, description="Target account UID for administrative wallet adjustment") payment_method: Optional[str] = "sandbox" notes: Optional[str] = None transaction_id: Optional[str] = Field(None, description="Client or caller specified transaction ID") idempotency_key: Optional[str] = Field(None, description="Idempotency key to guarantee single processing")
class PaymentIntentCreate(BaseModel): """Model for initializing a payment intent""" amount: float = Field(..., gt=0) currency: str = "INR" purpose: str = "order" # "order" or "wallet_topup" order_id: Optional[str] = None payment_method: Optional[str] = "sandbox"
class PaymentVerifyRequest(BaseModel): """Model for verifying a payment""" payment_id: str order_id: Optional[str] = None signature: Optional[str] = None
class ShopSettingsUpdate(BaseModel): """Model for shopkeeper settings and shop creation""" shop_name: Optional[str] = None category: Optional[str] = None owner_name: Optional[str] = None description: Optional[str] = None contact: Optional[str] = None email: Optional[str] = None phone: Optional[str] = None address: Optional[str] = None city: Optional[str] = None banner_url: Optional[str] = None logo_url: Optional[str] = None shop_photo: Optional[str] = None # Base64 or image URL strictly under 30KB is_created: Optional[bool] = None
class OrderResponse(BaseModel): """Complete order response""" id: str = Field(..., alias="_id") order_id: str buyer_uid: str buyer_email: str seller_uid: str # For single-seller orders items: List[OrderItem] subtotal: float shipping_cost: float tax: float total: float status: OrderStatus shipping_address: ShippingAddress billing_address: Optional[ShippingAddress] = None payment_method: str payment_status: str = "pending" tracking_number: Optional[str] = None notes: Optional[str] = None created_at: datetime updated_at: datetime shipped_at: Optional[datetime] = None delivered_at: Optional[datetime] = None
model_config = ConfigDict(populate_by_name=True)
# =========================================================# ANALYTICS MODELS# =========================================================
class AdEvent(BaseModel): """Ad interaction event""" ad_id: str event_type: str # "impression", "click", "conversion" user_id: Optional[str] = None session_id: Optional[str] = None device_type: Optional[str] = None platform: Optional[str] = None location: Optional[dict] = None source: str = "app" timestamp: datetime = Field(default_factory=datetime.utcnow)
class AdAnalytics(BaseModel): """Aggregated ad analytics""" ad_id: str date: str # YYYY-MM-DD impressions: int = 0 clicks: int = 0 conversions: int = 0 spent: float = 0.0 ctr: float = 0.0 # Click-through rate cpc: float = 0.0 # Cost per click conversion_rate: float = 0.0
ALLOWED_ADMOB_EVENT_TYPES = { "request", "loaded", "impression", "click", "failed_to_load", "failed_to_show", "dismissed"}
class AdmobEventCreate(BaseModel): """Event payload emitted by Flutter Google Mobile Ads SDK with strict validation (F-06)""" event_type: str = Field(..., max_length=32, description="Lifecycle event type") ad_unit_id: Optional[str] = Field(None, max_length=128) ad_format: Optional[str] = Field("interstitial", max_length=32) platform: Optional[str] = Field("android", max_length=16) is_test_ad: Optional[bool] = False error_code: Optional[int] = Field(None, ge=0, le=100000) error_message: Optional[str] = Field(None, max_length=256) placement: Optional[str] = Field(None, max_length=64) duration_seconds: Optional[int] = Field(5, ge=0, le=3600) user_id: Optional[str] = Field(None, max_length=128) metadata: Optional[Dict[str, Any]] = None timestamp: datetime = Field(default_factory=datetime.utcnow)
@field_validator('event_type') @classmethod def validate_event_type(cls, v: str) -> str: clean = (v or "").strip().lower() if clean not in ALLOWED_ADMOB_EVENT_TYPES: raise ValueError(f"Invalid AdMob event_type '{v}'. Must be one of: {sorted(ALLOWED_ADMOB_EVENT_TYPES)}") return clean
@field_validator('metadata') @classmethod def validate_metadata(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: if v is None: return None if len(v) > 10: raise ValueError("AdMob event metadata cannot exceed 10 keys") for key, val in v.items(): if len(str(key)) > 64: raise ValueError(f"Metadata key '{key}' exceeds 64 characters") if len(str(val)) > 256: raise ValueError(f"Metadata value for key '{key}' exceeds 256 characters") return v
@field_validator('ad_format') @classmethod def validate_ad_format(cls, v: Optional[str]) -> Optional[str]: if v is None: return v clean = v.strip().lower() if clean not in {"interstitial", "banner", "rewarded", "app_open"}: raise ValueError("Unsupported AdMob format") return clean
@field_validator('ad_unit_id') @classmethod def validate_ad_unit_id(cls, v: Optional[str]) -> Optional[str]: if v is not None: clean = v.strip() if not re.fullmatch(r"ca-app-pub-\d{16}/\d{10}", clean): raise ValueError("Invalid AdMob unit ID format") return clean return v
@field_validator('platform') @classmethod def validate_platform(cls, v: Optional[str]) -> Optional[str]: if v is None: return v clean = v.strip().lower() if clean not in {"android", "ios"}: raise ValueError("Unsupported AdMob platform") return clean
class AdmobConfigUpdate(BaseModel): """Dynamic AdMob Remote Configuration Update Payload""" ads_enabled: Optional[bool] = None real_ads_enabled: Optional[bool] = None min_seconds_between_ads: Optional[int] = None content_rating: Optional[str] = None banner_ads_enabled: Optional[bool] = None home_ads: Optional[bool] = None chat_ads: Optional[bool] = None hadith_ads: Optional[bool] = None tafsir_ads: Optional[bool] = None qaza_ads: Optional[bool] = None admob_app_id_android: Optional[str] = None admob_interstitial_id_android: Optional[str] = None admob_banner_id_android: Optional[str] = None admob_rewarded_id_android: Optional[str] = None admob_interstitial_id_ios: Optional[str] = None admob_banner_id_ios: Optional[str] = None
# =========================================================# BANK ACCOUNT & PAYOUT MODELS# =========================================================
class ShopkeeperBankDetails(BaseModel): """Bank account details for a shopkeeper to receive monthly settlements""" account_holder_name: str bank_name: str account_number: str ifsc_code: str upi_id: Optional[str] = None account_type: Optional[str] = "savings" # savings | current
class PlatformBankSettings(BaseModel): """Platform owner bank and payment gateway configuration""" account_holder_name: Optional[str] = None bank_name: Optional[str] = None account_number: Optional[str] = None ifsc_code: Optional[str] = None upi_id: Optional[str] = None gateway_provider: Optional[str] = "razorpay" # razorpay | stripe | direct_upi razorpay_key_id: Optional[str] = None razorpay_key_secret: Optional[str] = None google_play_license_key: Optional[str] = None platform_commission_percent: Optional[float] = 7.0 auto_settlement: Optional[bool] = True
class SubscriptionCreate(BaseModel): """Purchase a subscription tier""" plan_id: str billing_cycle: Optional[str] = "monthly" # monthly | annual payment_method: str = "google_play" # google_play | razorpay | upi | card purchase_token: Optional[str] = None # Google Play purchase token transaction_id: Optional[str] = None
# =========================================================# PROFESSIONAL ENTERPRISE USER ARCHITECTURE# =========================================================
class UserProfileModel(BaseModel): """User personal identity and localization""" display_name: str email: str phone: Optional[str] = None avatar_url: Optional[str] = None locale: str = "en" timezone: str = "Asia/Kolkata"
class UserAuthModel(BaseModel): """Access control, credentials and lifecycle status""" role: str = "USER" # "USER" | "MASJID_ADMIN" | "MUFTI" | "APP_ADMIN" | "ADMIN" provider: str = "google" # "password" | "google" | "phone" is_email_verified: bool = False status: str = "ACTIVE" # "ACTIVE" | "SUSPENDED" | "BANNED"
class UserMuftiAffiliation(BaseModel): """Mufti verification credentials and history""" is_mufti: bool = False status: str = "NONE" # "NONE" | "PENDING" | "APPROVED" | "REJECTED" applied_at: Optional[datetime] = None resolved_at: Optional[datetime] = None
class UserMasjidAffiliation(BaseModel): """Masjid administrative links and followed masjids""" managed_masjid_id: str = "" status: str = "NONE" # "NONE" | "PENDING" | "APPROVED" co_admin_masjids: List[str] = Field(default_factory=list) followed_masjids: List[str] = Field(default_factory=list)
class UserCommunityModel(BaseModel): """Community affiliations: Masjids & Mufti roles""" mufti: UserMuftiAffiliation = Field(default_factory=UserMuftiAffiliation) masjid: UserMasjidAffiliation = Field(default_factory=UserMasjidAffiliation)
class UserBusinessModel(BaseModel): """Business Suite: shops, advertisements, activation status""" is_enabled: bool = False activated_at: Optional[datetime] = None expires_at: Optional[datetime] = None is_expired: bool = False shop_id: Optional[str] = None wallet_balance: float = 0.0 total_ads_count: int = 0
class UserMetricsModel(BaseModel): """High-speed engagement counters for dashboards & analysis""" prayers_tracked: int = 0 consecutive_streak: int = 0 total_orders_placed: int = 0 total_spent_inr: float = 0.0 login_count: int = 1
class UserAnalyticsModel(BaseModel): """Telemetry, audit logs, DAU/MAU cohorts""" signup_platform: str = "android" # "android" | "web" | "ios" app_version: str = "1.0.0" created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) last_active_at: datetime = Field(default_factory=datetime.utcnow)
class UserFavoritesModel(BaseModel): """User favorites (Surahs & Ayahs) synchronized across devices""" surahs: List[dict] = Field(default_factory=list) ayahs: List[dict] = Field(default_factory=list)
class UserSubscriptionModel(BaseModel): """Subscription entitlements for all 5 canonical tiers + ₹5 acquisition offer""" is_pro: bool = False is_progress_plus: bool = False is_ad_free_admob: bool = False has_historical_progress: bool = False has_premium_themes: bool = False show_sponsored_card: bool = True plan_id: Optional[str] = "free" # "free" | "sahih_ad_free_monthly" | "sahih_progress_plus_monthly" | "sahih_pro_monthly" | "sahih_pro_6month" | "sahih_pro_yearly" | "sahih_pro_intro_5" tier: Optional[str] = "FREE" # "FREE" | "AD_FREE_ONLY" | "PROGRESS_PLUS" | "PRO" status: str = "FREE" # "FREE" | "ACTIVE" | "EXPIRED" | "CANCELLED" activated_at: Optional[datetime] = None expires_at: Optional[datetime] = None payment_method: Optional[str] = None # "razorpay" | "google_play" | "manual_grant" transaction_id: Optional[str] = None daily_ai_queries_used: int = 0 last_query_date: Optional[str] = None # YYYY-MM-DD has_claimed_intro_offer: bool = False intro_offer_claimed_at: Optional[datetime] = None intro_offer_declined_count: int = 0 intro_offer_last_declined_at: Optional[datetime] = None auto_renew: bool = True
class UserModel(BaseModel): """Root Enterprise User Document for MongoDB""" uid: str profile: UserProfileModel auth: UserAuthModel community: UserCommunityModel = Field(default_factory=UserCommunityModel) business: UserBusinessModel = Field(default_factory=UserBusinessModel) subscription: UserSubscriptionModel = Field(default_factory=UserSubscriptionModel) metrics: UserMetricsModel = Field(default_factory=UserMetricsModel) analytics: UserAnalyticsModel = Field(default_factory=UserAnalyticsModel) favorites: UserFavoritesModel = Field(default_factory=UserFavoritesModel)
# Legacy flat mirrors for zero-downtime backward compatibility username: Optional[str] = None email: Optional[str] = None role: Optional[str] = "USER" is_pro: bool = False mufti_status: Optional[str] = "NONE" masjid_status: Optional[str] = "NONE" managed_masjid_id: Optional[str] = "" followed_masjids: List[str] = Field(default_factory=list) is_business_enabled: bool = False business_activated_at: Optional[datetime] = None business_expires_at: Optional[datetime] = None has_shop: bool = False created_at: Optional[datetime] = None updated_at: Optional[datetime] = None
# =========================================================# PROFESSIONAL ENTERPRISE MASJID ARCHITECTURE# =========================================================
class MasjidContactModel(BaseModel): """Public contact info for community inquiries""" phone: Optional[str] = None email: Optional[str] = None website: Optional[str] = None
class MasjidIdentityModel(BaseModel): """Core public identity, fiqh, verification, and facilities""" name: str fiqh: str = "Sunni" # "Sunni" | "Shia" | "Ahmadi" description: Optional[str] = None is_verified: bool = False verified_at: Optional[datetime] = None facilities: List[str] = Field(default_factory=list) capacity: Optional[int] = None cover_image_url: Optional[str] = None gallery_urls: List[str] = Field(default_factory=list) contact: MasjidContactModel = Field(default_factory=MasjidContactModel)
class GeoPointModel(BaseModel): """Standard GeoJSON Point for MongoDB 2dsphere index""" type: str = "Point" coordinates: List[float] = Field(default_factory=lambda: [39.8262, 21.4225]) # [longitude, latitude]
class MasjidAddressModel(BaseModel): """Physical address hierarchy and localization""" country: str address_lines: List[str] = Field(default_factory=list) district: Optional[str] = None village: Optional[str] = None full_address: Optional[str] = None location_label: Optional[str] = None timezone_offset_hours: float = 5.5
class MasjidAdministrationModel(BaseModel): """Ownership, co-admin delegates, and status""" admin_uid: str co_admins: List[str] = Field(default_factory=list) approved_by: Optional[str] = None status: str = "APPROVED" # "PENDING" | "APPROVED" | "FLAGGED"
class PrayerTimeSlot(BaseModel): """Azan and Jamaat slot""" azan: str = "-" jamaat: str = "-"
class SunriseTimeSlot(BaseModel): time: str = "-"
class MasjidDailyPrayerModel(BaseModel): """5 daily prayer times + sunrise""" fajr: PrayerTimeSlot = Field(default_factory=PrayerTimeSlot) sunrise: SunriseTimeSlot = Field(default_factory=SunriseTimeSlot) zuhr: PrayerTimeSlot = Field(default_factory=PrayerTimeSlot) asr: PrayerTimeSlot = Field(default_factory=PrayerTimeSlot) maghrib: PrayerTimeSlot = Field(default_factory=PrayerTimeSlot) isha: PrayerTimeSlot = Field(default_factory=PrayerTimeSlot)
class MasjidJummaPrayerModel(BaseModel): """Friday congregation prayer schedules""" khutbah: str = "-" prayer: str = "-" shifts: List[str] = Field(default_factory=list)
class MasjidEidPrayerModel(BaseModel): """Eid prayers""" fitr: str = "-" adha: str = "-" is_enabled: bool = False
class MasjidHijriModel(BaseModel): """Local moon-sighting calendar calibration""" adjustment: int = 0 override: Optional[str] = None
class MasjidPrayersModel(BaseModel): """Consolidated prayer timing and automation systems""" daily: MasjidDailyPrayerModel = Field(default_factory=MasjidDailyPrayerModel) jumma: MasjidJummaPrayerModel = Field(default_factory=MasjidJummaPrayerModel) eid: MasjidEidPrayerModel = Field(default_factory=MasjidEidPrayerModel) hijri: MasjidHijriModel = Field(default_factory=MasjidHijriModel) automation_config: dict = Field(default_factory=dict)
class MasjidMetricsModel(BaseModel): """Pre-aggregated counters for fast dashboard ranking""" followers_count: int = 0 active_events_count: int = 0 reports_count: int = 0
class MasjidAuditModel(BaseModel): """Auditing and update timestamps""" created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) last_timings_updated_at: Optional[datetime] = None
class MasjidModel(BaseModel): """Master Enterprise Masjid Document""" masjid_id: str identity: MasjidIdentityModel location: GeoPointModel # GeoJSON Point for 2dsphere index address: MasjidAddressModel administration: MasjidAdministrationModel prayers: MasjidPrayersModel = Field(default_factory=MasjidPrayersModel) metrics: MasjidMetricsModel = Field(default_factory=MasjidMetricsModel) audit: MasjidAuditModel = Field(default_factory=MasjidAuditModel)
# Flat backward-compatibility fields (prevents breaking any existing Flutter screen) name: Optional[str] = None country: Optional[str] = None address_lines: List[str] = Field(default_factory=list) full_address: Optional[str] = None location_label: Optional[str] = None district: Optional[str] = None village: Optional[str] = None fiqh: Optional[str] = "Sunni" latitude: Optional[float] = None longitude: Optional[float] = None timezone_offset_hours: Optional[float] = 5.5 admin_uid: Optional[str] = None co_admins: List[str] = Field(default_factory=list) automation_config: Optional[dict] = None fajr_azan: Optional[str] = "-" fajr_jamaat: Optional[str] = "-" sunrise: Optional[str] = "-" zuhr_azan: Optional[str] = "-" zuhr_jamaat: Optional[str] = "-" asr_azan: Optional[str] = "-" asr_jamaat: Optional[str] = "-" maghrib_azan: Optional[str] = "-" maghrib_jamaat: Optional[str] = "-" isha_azan: Optional[str] = "-" isha_jamaat: Optional[str] = "-" jumma_khutbah: Optional[str] = "-" jumma_prayer: Optional[str] = "-" jumma_1st: Optional[str] = "-" jumma_2nd: Optional[str] = "-" jumma_3rd: Optional[str] = "-" eid_ul_fitr: Optional[str] = "-" eid_ul_adha: Optional[str] = "-" eid_enabled: Optional[bool] = False hijri_adjustment: Optional[int] = 0 hijri_override: Optional[str] = None clear_hijri_override: Optional[bool] = False region_id: Optional[str] = "kashmir" created_at: Optional[datetime] = None updated_at: Optional[datetime] = None
# =========================================================# ACCOUNT DELETION & REFUND REQUEST MODELS# =========================================================
class AccountDeleteRequest(BaseModel): """Payload for initiating a 7-day grace period account deletion""" password: Optional[str] = Field(None, description="Current password for email/password accounts") reauth_token: Optional[str] = Field(None, description="Fresh ID token or re-authentication proof for OAuth/Google accounts") reason: Optional[str] = Field(None, max_length=500, description="Optional user reason for deleting account") feedback: Optional[str] = Field(None, max_length=2000, description="Optional user feedback")
class AccountCancelDeleteRequest(BaseModel): """Payload for cancelling a pending account deletion during 7-day grace period""" reason: Optional[str] = Field(None, max_length=500, description="Reason for cancelling deletion")
class RefundReasonEnum(str, Enum): """Standardized user refund reasons""" ACCIDENTAL_PURCHASE = "ACCIDENTAL_PURCHASE" DUPLICATE_CHARGE = "DUPLICATE_CHARGE" SERVICE_DEFECT = "SERVICE_DEFECT" NOT_SATISFIED = "NOT_SATISFIED" OTHER = "OTHER"
class RefundRequestCreate(BaseModel): """Payload for submitting a user-facing refund request""" transaction_id: str = Field(..., min_length=1, max_length=128, description="Reference transaction ID") reason: str = Field(..., min_length=2, max_length=100, description="Refund reason code or title") reason_details: Optional[str] = Field(None, max_length=2000, description="Detailed explanation of the issue") amount: Optional[float] = Field(None, gt=0, description="Requested refund amount (defaults to max refundable)")
class RefundRequestReview(BaseModel): """SuperAdmin review action on a refund request""" status: str = Field(..., description="Target status: 'under_review', 'approved', or 'rejected'") admin_notes: Optional[str] = Field(None, max_length=2000, description="Internal administrator notes") rejection_reason: Optional[str] = Field(None, max_length=1000, description="Reason communicated if rejected")
class RefundRequestProcess(BaseModel): """SuperAdmin execution payload for processing an approved refund""" amount: Optional[float] = Field(None, gt=0, description="Override amount if partial refund") reason: Optional[str] = Field("Customer refund request approved", max_length=500) admin_notes: Optional[str] = Field(None, max_length=2000)
# =========================================================# HIJRI CALENDAR MODELS# =========================================================
class HijriCorrectionRequest(BaseModel): '''Payload for submitting a bounded adjustment or time-scoped temporary correction''' masjid_id: str effective_from: Optional[str] = Field(None, description='ISO date YYYY-MM-DD from which correction is active') effective_to: Optional[str] = Field(None, description='ISO date YYYY-MM-DD until which correction is active') hijri_year: Optional[int] = Field(None, ge=1400, le=1600, description='Corrected Hijri year') hijri_month: Optional[int] = Field(None, ge=1, le=12, description='Corrected Hijri month (1-12)') hijri_day: Optional[int] = Field(None, ge=1, le=30, description='Corrected Hijri day (1-30)') hijri_adjustment: Optional[int] = Field(None, ge=-3, le=3, description='Persistent day adjustment (-3 to +3)') reason: Optional[str] = Field(None, max_length=200, description='Verification reason or moon sighting authority source') clear_correction: Optional[bool] = Field(False, description='Set true to clear any existing temporary correction')
class MasjidIdPayload(BaseModel): '''Standard single masjid_id payload''' masjid_id: str123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""==============================================================================SAHIH ISLAM & PROJECT-X — CANONICAL MONEY & PASE DOMAIN ARCHITECTURE==============================================================================Centralized financial domain representation enforcing:1. Canonical integer minor unit (paise) representation (1 INR = 100 paise).2. Strict Decimal parsing rejecting fractional paise (>2 decimal places).3. Single transaction upper limit (₹10,00,000.00 / 100,000,000 paise).4. Finite number validation rejecting NaN, Infinity, -Infinity.5. Explicit currency validation (INR).6. Parameter conflict detection when both amount and amount_paise are provided.=============================================================================="""
from decimal import Decimal, InvalidOperationfrom typing import Union, Optional, Anyfrom fastapi import HTTPException
CANONICAL_CURRENCY = "INR"MAX_TRANSACTION_PAISE = 100_000_000 # ₹10,00,000.00MAX_TRANSACTION_RUPEES = 1_000_000.0
class Money: """ Immutable canonical monetary value object. Authoritative internal representation is always integer paise. """ __slots__ = ("_paise", "_currency")
def __init__(self, paise: int, currency: str = CANONICAL_CURRENCY): if not isinstance(paise, int): raise TypeError(f"Monetary paise must be an int, got {type(paise).__name__}") clean_curr = str(currency or CANONICAL_CURRENCY).strip().upper() if clean_curr != CANONICAL_CURRENCY: raise ValueError(f"Unsupported currency '{clean_curr}'. Only '{CANONICAL_CURRENCY}' is permitted.") self._paise = paise self._currency = clean_curr
@property def paise(self) -> int: return self._paise
@property def rupees(self) -> float: return round(self._paise / 100.0, 2)
@property def currency(self) -> str: return self._currency
@classmethod def from_paise(cls, paise: int, currency: str = CANONICAL_CURRENCY) -> "Money": return cls(paise=paise, currency=currency)
@classmethod def from_rupees( cls, value: Union[str, int, float, Decimal], allow_zero: bool = False, max_paise: int = MAX_TRANSACTION_PAISE, currency: str = CANONICAL_CURRENCY ) -> "Money": """ Parses a rupee monetary input strictly via Decimal. Rejects fractional paise (>2 decimal places), NaN, Infinity, and out-of-bound amounts. """ try: dec = Decimal(str(value).strip()) except (InvalidOperation, TypeError, ValueError): raise HTTPException(status_code=400, detail="Invalid monetary amount format.")
if not dec.is_finite(): raise HTTPException(status_code=400, detail="Monetary amount must be a finite number.")
if dec.as_tuple().exponent < -2: raise HTTPException( status_code=400, detail="Invalid monetary precision: fractional paise is not permitted." )
clean_rupees = dec.quantize(Decimal("0.01")) paise = int(round(clean_rupees * 100))
if not allow_zero and paise <= 0: raise HTTPException(status_code=400, detail="Monetary amount must be strictly positive.") if paise < 0: raise HTTPException(status_code=400, detail="Monetary amount cannot be negative.") if paise > max_paise: max_inr = max_paise / 100.0 raise HTTPException( status_code=400, detail=f"Adjustment amount exceeds maximum single transaction limit / exceeds single transaction cap of ₹{max_inr:,.2f} ({max_paise} paise)." )
return cls(paise=paise, currency=currency)
@classmethod def parse( cls, amount: Optional[Union[str, int, float, Decimal]] = None, amount_paise: Optional[int] = None, allow_zero: bool = False, max_paise: int = MAX_TRANSACTION_PAISE, currency: str = CANONICAL_CURRENCY ) -> "Money": """ Unified parser accepting amount (rupees), amount_paise, or both. Enforces agreement if both are provided. """ if amount_paise is not None: if not isinstance(amount_paise, int): try: amount_paise = int(amount_paise) except (ValueError, TypeError): raise HTTPException(status_code=400, detail="amount_paise must be an integer.") if not allow_zero and amount_paise <= 0: raise HTTPException(status_code=400, detail="amount_paise must be strictly positive.") if amount_paise < 0: raise HTTPException(status_code=400, detail="amount_paise cannot be negative.") if amount_paise > max_paise: raise HTTPException( status_code=400, detail=f"amount_paise exceeds maximum limit of {max_paise} paise." )
# If amount (rupees) was also passed, verify exact match if amount is not None: m_from_rupees = cls.from_rupees(amount, allow_zero=allow_zero, max_paise=max_paise, currency=currency) if m_from_rupees.paise != amount_paise: raise HTTPException( status_code=400, detail=f"Contradictory monetary parameters: amount={amount} (₹{m_from_rupees.rupees}) " f"does not match amount_paise={amount_paise}." ) return cls(paise=amount_paise, currency=currency)
if amount is not None: return cls.from_rupees(amount, allow_zero=allow_zero, max_paise=max_paise, currency=currency)
raise HTTPException(status_code=400, detail="Either 'amount' (rupees) or 'amount_paise' must be provided.")
def __add__(self, other: "Money") -> "Money": if not isinstance(other, Money): return NotImplemented return Money(paise=self._paise + other._paise, currency=self._currency)
def __sub__(self, other: "Money") -> "Money": if not isinstance(other, Money): return NotImplemented return Money(paise=self._paise - other._paise, currency=self._currency)
def __eq__(self, other: Any) -> bool: if isinstance(other, Money): return self._paise == other._paise and self._currency == other._currency return False
def __lt__(self, other: "Money") -> bool: if isinstance(other, Money): return self._paise < other._paise return NotImplemented
def __le__(self, other: "Money") -> bool: if isinstance(other, Money): return self._paise <= other._paise return NotImplemented
def __gt__(self, other: "Money") -> bool: if isinstance(other, Money): return self._paise > other._paise return NotImplemented
def __ge__(self, other: "Money") -> bool: if isinstance(other, Money): return self._paise >= other._paise return NotImplemented
def __repr__(self) -> str: return f"Money({self._paise} paise, ₹{self.rupees:.2f} {self._currency})"
def __str__(self) -> str: return f"₹{self.rupees:.2f}"
def parse_money( amount: Optional[Union[str, int, float, Decimal]] = None, amount_paise: Optional[int] = None, allow_zero: bool = False, max_paise: int = MAX_TRANSACTION_PAISE, currency: str = CANONICAL_CURRENCY) -> Money: """Convenience helper for Money.parse.""" return Money.parse( amount=amount, amount_paise=amount_paise, allow_zero=allow_zero, max_paise=max_paise, currency=currency )
def paise_to_rupees(paise: int) -> float: return round(int(paise) / 100.0, 2)
def rupees_to_paise(rupees: Union[float, Decimal, str, int]) -> int: return Money.from_rupees(rupees, allow_zero=True).paise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357# =========================================================# 1. IMPORTS & SETUP# =========================================================import loggingimport datetimeimport asynciofrom typing import Optionalfrom fastapi import APIRouter, Request, HTTPException, status, Dependsfrom fastapi.responses import JSONResponse, Responsefrom pydantic import BaseModel, Field, field_validator, model_validatorfrom anyio import to_thread
from app.database import ( users_collection, pending_approvals_collection, verified_role_records_collection, mufti_hadiths_collection,)from app.limiter import limiterfrom app.auth_deps import require_admin, require_verified_mufti, get_current_user, invalidate_user_cachefrom app import realtimefrom app.role_application_helpers import ( archive_or_purge_application, decode_and_validate_pdf_data_uri, decode_data_uri_bytes, sanitize_social_profile, validate_dob, validate_phone_with_country_code,)
# --- ENTERPRISE LOGGING ---logger = logging.getLogger("sahihislam.mufti")logger.setLevel(logging.INFO)
router = APIRouter()
# =========================================================# 2. PYDANTIC SCHEMAS (Strict Input Validation)# =========================================================class MuftiRegistration(BaseModel): # `userId` is accepted for backwards compatibility with the # Flutter app, but the server IGNORES it (audit C1) and uses # the verified Firebase token's uid instead. userId: Optional[str] = Field(default=None, max_length=256) full_name: str = Field(..., min_length=2, max_length=120) dob: str = Field(..., min_length=10, max_length=10) fathers_name: str = Field(..., min_length=2, max_length=120) phone: str = Field(..., min_length=8, max_length=30) country_state: str = Field(..., min_length=2, max_length=120) city_district: str = Field(..., min_length=2, max_length=120) town_village: str = Field(..., min_length=2, max_length=120) proof_pdf_base64: str = Field(..., min_length=10) proof_pdf_name: Optional[str] = Field(default="mufti_proof.pdf", max_length=180) social_media_profile: Optional[str] = Field(default=None, max_length=300) # Optional legacy aliases retained for backward display compatibility name: Optional[str] = Field(default=None, max_length=120) district: Optional[str] = Field(default=None, max_length=120)
@field_validator("full_name", "fathers_name", "country_state", "city_district", "town_village") @classmethod def _strip_required_text(cls, v: str) -> str: cleaned = v.strip() if len(cleaned) < 2: raise ValueError("Field must contain at least 2 characters") return cleaned
@field_validator("dob") @classmethod def _check_dob(cls, v: str) -> str: return validate_dob(v)
@field_validator("phone") @classmethod def _check_phone(cls, v: str) -> str: return validate_phone_with_country_code(v)
@field_validator("social_media_profile") @classmethod def _check_social(cls, v: Optional[str]) -> str: return sanitize_social_profile(v)
@model_validator(mode="after") def _normalize_proof_and_aliases(self): normalized_pdf, _ = decode_and_validate_pdf_data_uri(self.proof_pdf_base64) self.proof_pdf_base64 = normalized_pdf self.name = self.full_name self.district = self.city_district return self
class MuftiResolve(BaseModel): target_uid: str action: str = Field(..., pattern="^(APPROVE|REJECT)$") role: Optional[str] = None # ✅ Added to prevent 422 errors from Flutter Admin Dashboard reason: Optional[str] = None
class HadithUpload(BaseModel): # uploader_id is kept in the schema for backwards compatibility # with the Flutter app, but the server IGNORES it. The verified # Firebase token's uid is the only source of truth (see audit C5). uploader_id: Optional[str] = None hadith_id: Optional[str] = Field(default=None, max_length=64) collection: Optional[str] = Field(default="Unknown", max_length=64) volume: Optional[str] = Field(default="1", max_length=16) book_no: Optional[str] = Field(default="1", max_length=16) book_name: Optional[str] = Field(default="General", max_length=200) chapter_no: Optional[str] = Field(default="1", max_length=16) chapter_name: Optional[str] = Field(default="General", max_length=200) topic: Optional[str] = Field(default="General", max_length=200) narrator: Optional[str] = Field(default="Unknown", max_length=200) source: Optional[str] = Field(default="General", max_length=200) # H1: cap user-supplied free text. 5 KB is plenty for a hadith body # and stops a single upload from consuming embedding CPU/RAM. text_english: str = Field(..., min_length=10, max_length=5000) text_arabic: str = Field(..., min_length=5, max_length=5000) text_urdu: Optional[str] = Field(default=None, max_length=5000) text_hinglish: Optional[str] = Field(default=None, max_length=5000) reference: Optional[str] = Field(default=None, max_length=200) grade: Optional[str] = Field(default="Unverified", max_length=64)
# =========================================================# 3. MUFTI REGISTRATION# =========================================================@router.post('/register')@limiter.limit("1200/minute")async def register_mufti( payload: MuftiRegistration, request: Request, user: dict = Depends(get_current_user),): """Submits a mufti application.
Auth-gated: a valid Firebase ID token is required. The body's `userId` field is ignored — the verified uid wins, so an attacker cannot submit an application on behalf of someone else (audit C1).""" try: # Identity: token wins, body is ignored. verified_uid = user["uid"]
mufti_data = payload.model_dump() # Strip the client-supplied userId so it never gets persisted. mufti_data.pop("userId", None) _, pdf_bytes_len = decode_and_validate_pdf_data_uri(payload.proof_pdf_base64) mufti_data.update({ "uid": verified_uid, "name": payload.full_name, "district": payload.city_district, "proof_pdf_name": (payload.proof_pdf_name or "mufti_proof.pdf").strip() or "mufti_proof.pdf", "proof_pdf_size_bytes": pdf_bytes_len, "social_media_profile": payload.social_media_profile or "", "role": "MUFTI", "status": "PENDING", "timestamp": datetime.datetime.utcnow(), })
# 🚀 PERFORMANCE: Parallelize approvals update & user status update await asyncio.gather( pending_approvals_collection.update_one( {"uid": verified_uid, "role": "MUFTI"}, {"$set": mufti_data}, upsert=True ), users_collection.update_one( {"uid": verified_uid}, { "$set": {"mufti_status": "PENDING"}, "$unset": {"mufti_rejection_reason": ""}, }, ) ) await invalidate_user_cache(verified_uid)
logger.info(f"New Mufti application from: {verified_uid}")
# Real-time: fan out to every connected admin so the app # admin dashboard updates without a refresh. try: admin_uids = [ u["uid"] async for u in users_collection.find( {"role": {"$in": ["ADMIN", "APP_ADMIN"]}}, {"uid": 1, "_id": 0} ) ] realtime.publish_bulk( admin_uids, "new_pending_request", {"role": "MUFTI", "uid": verified_uid}, ) except Exception as pub_e: # Never let a realtime failure break a successful write. logger.warning("realtime: publish new_pending_request failed: %s", pub_e)
return JSONResponse(status_code=201, content={"message": "Mufti application submitted successfully"}) except Exception as e: logger.error(f"Mufti Registration Error: {e}") raise HTTPException(status_code=500, detail="Internal Server Error")
# =========================================================# 4. RESOLVE MUFTI (ADMIN)# =========================================================@router.post('/resolve')@limiter.limit("20/minute")async def resolve_mufti(payload: MuftiResolve, request: Request, admin: dict = Depends(require_admin)): try: now_iso = datetime.datetime.utcnow().isoformat() admin_identity = admin.get("uid") or admin.get("email") or "unknown" if payload.action == "APPROVE": await users_collection.update_one( {"uid": payload.target_uid}, { "$set": {"mufti_status": "APPROVED"}, "$unset": {"mufti_rejection_reason": ""}, }, ) logger.info(f"Admin APPROVED Mufti: {payload.target_uid}") else: rej_reason = (payload.reason or "").strip() await users_collection.update_one( {"uid": payload.target_uid}, { "$set": { "mufti_status": "REJECTED", "mufti_rejection_reason": rej_reason, } } ) logger.info(f"Admin REJECTED Mufti: {payload.target_uid} - Reason: {rej_reason}")
await archive_or_purge_application( pending_approvals_collection, verified_role_records_collection, target_uid=payload.target_uid, role="MUFTI", action=payload.action, admin_uid=admin_identity, resolved_at=now_iso, ) await invalidate_user_cache(payload.target_uid)
# Real-time: notify the applicant so their app can flip from # "Pending" to "Approved" / "Rejected" without a refresh. realtime.publish( payload.target_uid, "mufti_resolved", {"action": payload.action, "reason": payload.reason}, )
# Real-time: notify other App Admins so their dashboard list updates seamlessly try: admin_uids = [ u["uid"] async for u in users_collection.find( {"role": {"$in": ["ADMIN", "APP_ADMIN"]}}, {"uid": 1, "_id": 0} ) ] realtime.publish_bulk( admin_uids, "pending_request_resolved", { "uid": payload.target_uid, "role": "MUFTI", "action": payload.action, "admin_name": admin.get("username") or admin.get("email") or "Admin", }, ) except Exception as pub_e: logger.warning("realtime: publish pending_request_resolved failed: %s", pub_e)
return {"status": "success"} except HTTPException: raise except Exception as e: logger.error(f"Mufti Resolution Error: {e}") raise HTTPException(status_code=500, detail="Internal Server Error")
@router.get('/application-proof/{target_uid}')async def get_mufti_application_proof(target_uid: str, admin: dict = Depends(require_admin)): """Downloads or views a pending or verified Mufti's proof PDF document.""" projection = {"_id": 0, "proof_pdf_base64": 1, "proof_pdf_name": 1} doc = await pending_approvals_collection.find_one( {"uid": target_uid, "role": "MUFTI"}, projection, ) if not doc or not doc.get("proof_pdf_base64"): doc = await verified_role_records_collection.find_one( {"uid": target_uid, "role": "MUFTI"}, projection, ) if not doc or not doc.get("proof_pdf_base64"): raise HTTPException(status_code=404, detail="Mufti proof document not found")
try: raw_bytes, media_type = decode_data_uri_bytes(doc["proof_pdf_base64"]) except Exception as exc: raise HTTPException(status_code=500, detail="Stored proof document is unreadable") from exc
safe_name = (doc.get("proof_pdf_name") or "mufti_proof.pdf").replace('"', "") if not safe_name.lower().endswith(".pdf"): safe_name = f"{safe_name}.pdf"
return Response( content=raw_bytes, media_type=media_type or "application/pdf", headers={"Content-Disposition": f'inline; filename="{safe_name}"'}, )
# =========================================================# 5. MUFTI PANEL: UPLOAD & VERIFY HADITH# =========================================================@router.post('/upload-hadith')@limiter.limit("10/minute")async def upload_hadith(payload: HadithUpload, request: Request, user: dict = Depends(require_verified_mufti)): try: # 1. Identity is the VERIFIED TOKEN, never the request body. # require_verified_mufti has already enforced # mufti_status==APPROVED against Mongo (audit C5). verified_uid = user["uid"] actual_name = user.get("username", "Verified Scholar")
# 2. Prepare text for AI Vectorization text_to_embed = f"{payload.text_english} {payload.narrator} {payload.reference}"
# 3. NON-BLOCKING AI EMBEDDING GENERATION (Cloud-Aware & Resilient) try: from app.inference_client import get_embedding embedding_vector = (await get_embedding(text_to_embed)).tolist() except Exception as e: logger.error(f"❌ Embedding Generation Failed: {e}") raise HTTPException(status_code=500, detail="AI Vectorization failed")
# 4. Construct DB Entry hadith_entry = payload.dict(exclude={"uploader_id"}) hadith_entry.update({ "uploader_id": verified_uid, # always the token uid "mufti_name": actual_name, # Use the SAME field name as the seeded Bukhari collection # (`embedding`, 1024-d from bge-m3) so the Atlas vector index # `sahihislam1024_index` (defined on `embedding` in # database.py) finds these rows. The whole stack is 1024-d. "embedding": embedding_vector, "is_mufti_verified": True, "timestamp": datetime.datetime.utcnow() })
# 5. Insert to DB result = await mufti_hadiths_collection.insert_one(hadith_entry)
if result.inserted_id: logger.info(f"Hadith uploaded and indexed by Mufti: {actual_name} ({verified_uid})") return JSONResponse(status_code=201, content={"message": "Verified and indexed"})
raise HTTPException(status_code=500, detail="Database insertion failed")
except HTTPException: raise except Exception as e: logger.error(f"Hadith Upload Error: {e}") raise HTTPException(status_code=500, detail="Internal Server Error").env.development.exampleAdded+67
.env.exampleAdded+267
.env.production.exampleAdded+69
.env.staging.exampleAdded+64
.gitattributesAdded+1
.gitignoreAdded+104
R2_INTEGRATION_SUMMARY.mdAdded+295
README.mdAdded+53
README_APP.mdAdded+50
README_SUPERADMIN.mdAdded+53
RELEASE_VERSIONAdded+1
app.pyAdded+488
app/__init__.pyAdded+1
app/ads_routes.pyAdded+1906
app/api/__init__.pyAdded
app/api/contact.pyAdded+168
app/api/razorpay_standard.pyAdded+1161
app/api/v1/__init__.pyAdded+14
app/api/v1/prayer.pyAdded+124
app/api/v1/quran.pyAdded+33
app/auth.pyAdded
app/auth_deps.pyAdded+806
app/content_moderation.pyAdded+599
app/core/__init__.pyAdded
app/core/app_release.pyAdded+101
app/core/config.pyAdded+771
app/core/media_token.pyAdded+160
app/core/rate_limits.pyAdded+324
app/core/runtime_settings.pyAdded+612
app/core/security.pyAdded+154
app/crypto_security.pyAdded+18
app/database.pyAdded+4
app/events_routes.pyAdded+1038
app/geocoding.pyAdded+10
app/hadith.pyAdded
app/hijri.pyAdded+188
app/inference_client.pyAdded+13
app/infrastructure/__init__.pyAdded
app/infrastructure/database.pyAdded+6
app/infrastructure/firebase.pyAdded+242
app/infrastructure/mongodb.pyAdded+1511
app/infrastructure/redis.pyAdded+576
app/infrastructure/storage.pyAdded+823
app/intent_router.pklAdded
app/limiter.pyAdded+9
app/main.pyAdded+7
app/masjid_routes.pyAdded
app/models.pyAdded+951
app/money.pyAdded+207
app/mufti_routes.pyAdded+357