"""Shared Django settings for all environments.""" import json import os from pathlib import Path from urllib.parse import urlparse BASE_DIR = Path(__file__).resolve().parent.parent.parent def env(key: str, default: str | None = None) -> str | None: return os.environ.get(key, default) def env_bool(key: str, default: bool = False) -> bool: value = os.environ.get(key) if value is None: return default return value.lower() in {"1", "true", "yes", "on"} def env_list(key: str, default: str = "") -> list[str]: value = os.environ.get(key, default) if not value: return [] value = value.strip() if value.startswith("["): try: parsed = json.loads(value) except ValueError: parsed = None if isinstance(parsed, list): return [str(item).strip() for item in parsed if str(item).strip()] return [item.strip() for item in value.split(",") if item.strip()] def database_config() -> dict: database_url = env("DATABASE_URL") if database_url: parsed = urlparse(database_url) return { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": parsed.path.lstrip("/"), "USER": parsed.username or "", "PASSWORD": parsed.password or "", "HOST": parsed.hostname or "", "PORT": str(parsed.port or 5432), } } if env("DB_HOST"): return { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env("DB_NAME", "scha"), "USER": env("DB_USER", "scha"), "PASSWORD": env("DB_PASSWORD", ""), "HOST": env("DB_HOST"), "PORT": env("DB_PORT", "5432"), } } return { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } def build_csrf_trusted_origins( allowed_hosts: list[str], explicit: list[str] | None = None ) -> list[str]: """Build CSRF_TRUSTED_ORIGINS for Django 4+ Origin checks on HTTPS POSTs.""" if explicit: return explicit local_hosts = {"localhost", "127.0.0.1", "0.0.0.0"} origins: list[str] = [] for host in allowed_hosts: if not host or host == "*" or host.startswith("."): continue hostname = host.split(":")[0] scheme = "http" if hostname in local_hosts else "https" origins.append(f"{scheme}://{host}") return origins SECRET_KEY = env( "DJANGO_SECRET_KEY", "django-insecure-dev-only-change-me-before-production", ) DEBUG = env_bool("DJANGO_DEBUG", False) allowed_hosts = env_list("DJANGO_ALLOWED_HOSTS", "*") ALLOWED_HOSTS = allowed_hosts if allowed_hosts else ["*"] CSRF_TRUSTED_ORIGINS = build_csrf_trusted_origins( ALLOWED_HOSTS, env_list("DJANGO_CSRF_TRUSTED_ORIGINS"), ) INSTALLED_APPS = [ "schasite.apps.SchasiteConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "whitenoise.runserver_nostatic", "django.contrib.staticfiles", "phonenumber_field", "django_recaptcha", ] 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 = "scha.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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 = "scha.wsgi.application" DATABASES = database_config() 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", }, ] LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True STATIC_URL = "static/" STATIC_ROOT = BASE_DIR / "staticfiles" STORAGES = { "staticfiles": { "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", }, } DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" STRIPE_PUBLISHABLE_KEY = env("STRIPE_PUBLISHABLE_KEY", "") STRIPE_SECRET_KEY = env("STRIPE_SECRET_KEY", "") STRIPE_ENDPOINT_SECRET = env("STRIPE_ENDPOINT_SECRET", "") RECAPTCHA_PUBLIC_KEY = env("RECAPTCHA_PUBLIC_KEY", "") RECAPTCHA_PRIVATE_KEY = env("RECAPTCHA_PRIVATE_KEY", "")