quantum-ai/netcop_hub/settings.py
Claude 74ff5c4ea6 🔧 Fix email verification 'Not Found' error
 Root Cause Fixed:
- SITE_URL was pointing to quantumtaskai.com instead of actual Railway domain
- Email verification links were going to wrong domain causing 404 errors

🔧 Changes Made:
- Update SITE_URL to use quantum-ai.up.railway.app for Railway environment
- Email verification links now point to correct domain

🛠️ Added Management Command:
- Create verify_email command for manual email verification
- Usage: python manage.py verify_email user@example.com
- Useful for admin-created users or troubleshooting

 Expected Result:
- Email verification links now work correctly
- Users can successfully verify their emails
- Manual verification available for admin use

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-26 23:37:17 +05:30

454 lines
14 KiB
Python

"""
Django settings for netcop_hub project.
Generated by 'django-admin startproject' using Django 5.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""
from pathlib import Path
from decouple import config
import sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Add apps directory to Python path
sys.path.insert(0, str(BASE_DIR / 'apps'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# Validate required environment variables
required_env_vars = ['SECRET_KEY']
# Add production-specific required variables when DEBUG=False
debug_mode = config('DEBUG', default=True, cast=bool)
if not debug_mode:
required_env_vars.extend([
'ALLOWED_HOSTS',
'EMAIL_HOST_USER',
'EMAIL_HOST_PASSWORD',
'STRIPE_SECRET_KEY',
])
missing_vars = [var for var in required_env_vars if not config(var, default='')]
if missing_vars:
import sys
print(f"❌ Missing required environment variables: {', '.join(missing_vars)}")
print("💡 Please create a .env file based on .env.example")
print("💡 For local development, copy .env.example to .env and fill in the values")
print("💡 For production, ensure all required environment variables are set")
sys.exit(1)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', default=True, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='localhost,127.0.0.1,testserver,quantumtaskai.com').split(',')
# Site URL configuration for emails
if config('RAILWAY_ENVIRONMENT', default=''):
# Use actual Railway domain for email verification links
SITE_URL = 'https://quantum-ai.up.railway.app'
else:
SITE_URL = config('SITE_URL', default='http://localhost:8000')
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'authentication',
'wallet',
'core',
'agent_base',
'weather_reporter',
'data_analyzer',
'job_posting_generator',
'social_ads_generator',
'email_writer',
'five_whys_analyzer',
]
# Development apps (only in DEBUG mode)
if DEBUG:
try:
import debug_toolbar
INSTALLED_APPS += ['debug_toolbar']
except ImportError:
pass
try:
import django_extensions
INSTALLED_APPS += ['django_extensions']
except ImportError:
pass
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Development middleware (only in DEBUG mode)
if DEBUG:
try:
import debug_toolbar
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']
# Debug toolbar configuration
INTERNAL_IPS = ['127.0.0.1', 'localhost']
except ImportError:
pass
# Security Headers
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'
# Production security settings (applied when DEBUG=False)
if not DEBUG:
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_HTTPONLY = True
ROOT_URLCONF = 'netcop_hub.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'netcop_hub.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases
import dj_database_url
# Smart database configuration: Auto-detect environment
database_url = config('DATABASE_URL', default='')
if database_url:
# Parse the provided DATABASE_URL (Railway PostgreSQL)
DATABASES = {
'default': dj_database_url.parse(database_url, conn_max_age=600)
}
elif config('RAILWAY_ENVIRONMENT', default=''):
# Railway environment without DATABASE_URL (shouldn't happen, but fallback)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('PGDATABASE', default='railway'),
'USER': config('PGUSER', default='postgres'),
'PASSWORD': config('PGPASSWORD', default=''),
'HOST': config('PGHOST', default='localhost'),
'PORT': config('PGPORT', default='5432'),
}
}
else:
# Local development: Default to SQLite for reliability
# Users can override with DATABASE_URL if they want PostgreSQL
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Optional: Check if user wants PostgreSQL (via environment or file)
postgres_preference = config('USE_POSTGRESQL', default='False').lower()
if postgres_preference in ['true', '1', 'yes']:
try:
import psycopg2
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('PGDATABASE', default='netcop_hub'),
'USER': config('PGUSER', default='netcop_user'),
'PASSWORD': config('PGPASSWORD'),
'HOST': config('PGHOST', default='localhost'),
'PORT': config('PGPORT', default='5432'),
}
}
except ImportError:
# psycopg2 not available - stick with SQLite
pass
# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Custom user model
AUTH_USER_MODEL = 'authentication.User'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
# WhiteNoise configuration for static files in production
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
WHITENOISE_USE_FINDERS = True
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Stripe
STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY', default='')
STRIPE_WEBHOOK_SECRET = config('STRIPE_WEBHOOK_SECRET', default='')
# AI Assistant Webhooks
N8N_WEBHOOK_DATA_ANALYZER = config('N8N_WEBHOOK_DATA_ANALYZER', default='')
N8N_WEBHOOK_FIVE_WHYS = config('N8N_WEBHOOK_FIVE_WHYS', default='')
N8N_WEBHOOK_JOB_POSTING = config('N8N_WEBHOOK_JOB_POSTING', default='')
N8N_WEBHOOK_FAQ_GENERATOR = config('N8N_WEBHOOK_FAQ_GENERATOR', default='')
N8N_WEBHOOK_SOCIAL_ADS = config('N8N_WEBHOOK_SOCIAL_ADS', default='')
# OpenWeather API
OPENWEATHER_API_KEY = config('OPENWEATHER_API_KEY', default='')
# Email Configuration
# Use SMTP backend in production, console in development
if DEBUG:
EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend')
else:
EMAIL_BACKEND = config('EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
EMAIL_HOST = config('EMAIL_HOST', default='smtp.gmail.com')
EMAIL_PORT = config('EMAIL_PORT', default=587, cast=int)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=True, cast=bool)
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
EMAIL_FILE_PATH = config('EMAIL_FILE_PATH', default='/tmp/app-messages')
DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default='Quantum Tasks AI <noreply@quantumtaskai.com>')
# Email timeout settings for production stability
EMAIL_TIMEOUT = 30
# Security settings
CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in config('CSRF_TRUSTED_ORIGINS', default='').split(',') if origin.strip()]
# Always include common development origins
CSRF_TRUSTED_ORIGINS.extend([
'http://localhost:8000',
'http://127.0.0.1:8000',
'https://localhost:8000',
'https://127.0.0.1:8000'
])
# Add Railway domain if running on Railway
if config('RAILWAY_ENVIRONMENT', default=''):
# Add known Railway domain
CSRF_TRUSTED_ORIGINS.append('https://quantum-ai.up.railway.app')
# Try to get Railway public domain from environment
railway_url = config('RAILWAY_PUBLIC_DOMAIN', default='')
if railway_url and f'https://{railway_url}' not in CSRF_TRUSTED_ORIGINS:
CSRF_TRUSTED_ORIGINS.append(f'https://{railway_url}')
# Also add production domain
CSRF_TRUSTED_ORIGINS.append('https://quantumtaskai.com')
# Railway-specific optimizations
USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True
# Database connection optimization for Railway PostgreSQL
if 'default' in DATABASES:
DATABASES['default']['CONN_MAX_AGE'] = 600 # 10 minutes connection pooling
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Caching Configuration
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.redis.RedisCache',
'LOCATION': config('REDIS_URL', default='redis://127.0.0.1:6379/1'),
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
},
'KEY_PREFIX': 'quantumtaskai',
'TIMEOUT': 300, # 5 minutes default
'VERSION': 1,
}
}
# Fallback to locmem cache if Redis not available
try:
import redis
# Test Redis connection
redis_client = redis.from_url(config('REDIS_URL', default='redis://127.0.0.1:6379/1'))
redis_client.ping()
except (ImportError, Exception):
# Use memory cache if Redis not available or can't connect
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'quantumtaskai-cache',
'OPTIONS': {
'MAX_ENTRIES': 1000,
'CULL_FREQUENCY': 3,
}
}
}
# Session Configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 3600 # 1 hour
SESSION_SAVE_EVERY_REQUEST = True
# Authentication URLs
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/admin/' # Redirect to admin after admin login
LOGOUT_REDIRECT_URL = '/'
# Logging Configuration
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': 'netcop.log',
'formatter': 'verbose',
},
'console': {
'level': 'DEBUG' if DEBUG else 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
'loggers': {
'django': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
'netcop_hub': {
'handlers': ['console', 'file'],
'level': 'DEBUG' if DEBUG else 'INFO',
'propagate': False,
},
'agent_base': {
'handlers': ['console', 'file'],
'level': 'DEBUG' if DEBUG else 'INFO',
'propagate': False,
},
'wallet': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
'agent_base.security': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
'authentication.security': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
'core.security': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
'wallet.security': {
'handlers': ['console', 'file'],
'level': 'INFO',
'propagate': False,
},
},
}