quantum-ai/netcop_hub/settings.py
Claude a6e9ca54d6 Fix security vulnerabilities and improve environment configuration
- Remove hardcoded SECRET_KEY from settings.py (now requires env var)
- Remove hardcoded database credentials from PostgreSQL config
- Add environment variable validation on Django startup
- Fix Stripe API key logging to prevent credential exposure
- Update .env.example to match Railway deployment structure
- Replace exposed API key in documentation with placeholder
- Maintain compatibility with existing Railway deployment setup

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-13 12:30:23 +05:30

240 lines
7.4 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']
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")
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,netcop.up.railway.app').split(',')
# 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',
'five_whys_analyzer',
]
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',
]
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
DATABASES = {
'default': dj_database_url.parse(database_url)
}
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='')
# Security settings
CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in config('CSRF_TRUSTED_ORIGINS', default='').split(',') if origin.strip()]
# Add Railway domain if running on Railway
if config('RAILWAY_ENVIRONMENT', default=''):
railway_url = config('RAILWAY_PUBLIC_DOMAIN', default='')
if railway_url:
CSRF_TRUSTED_ORIGINS.append(f'https://{railway_url}')
# Also add common Railway domain pattern
CSRF_TRUSTED_ORIGINS.append('https://netcop.up.railway.app')
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'
# Authentication URLs
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'