Add secret management guide, client-side performance monitoring, and search accessibility enhancements

- Introduced a comprehensive Secret Management Guide detailing best practices, secret classification, development setup, production management, rotation procedures, and emergency protocols.
- Implemented a client-side performance monitoring script to track various metrics including page load performance, paint metrics, layout shifts, and memory usage.
- Enhanced search accessibility with keyboard navigation support for search results, ensuring compliance with WCAG standards and improving user experience.
This commit is contained in:
pacnpal
2025-12-23 16:41:42 -05:00
parent ae31e889d7
commit edcd8f2076
155 changed files with 22046 additions and 4645 deletions

View File

@@ -5,12 +5,18 @@ It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
This module is used for production deployments with ASGI servers like Uvicorn.
The settings module defaults to production, but can be overridden via the
DJANGO_SETTINGS_MODULE environment variable.
"""
import os
from django.core.asgi import get_asgi_application
# Default to production settings for ASGI deployments
# This can be overridden by setting DJANGO_SETTINGS_MODULE environment variable
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.django.production")
application = get_asgi_application()

View File

@@ -1,250 +0,0 @@
"""
Django settings for thrillwiki project.
"""
from pathlib import Path
import os
import sys
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Add apps directory to sys.path so Django can find the apps
apps_dir = BASE_DIR / "apps"
if apps_dir.exists() and str(apps_dir) not in sys.path:
sys.path.insert(0, str(apps_dir))
SECRET_KEY = "django-insecure-=0)^0#h#k$0@$8$ys=^$0#h#k$0@$8$ys=^"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CSRF_TRUSTED_ORIGINS = ["https://beta.thrillwiki.com"]
ALLOWED_HOSTS = ["*"]
# GeoDjango Settings
GDAL_LIBRARY_PATH = "/opt/homebrew/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/opt/homebrew/lib/libgeos_c.dylib"
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
"django.contrib.gis", # Add GeoDjango
"rest_framework", # Django REST Framework
"rest_framework.authtoken", # Token authentication
"pghistory", # Add django-pghistory
"pgtrigger", # Required by django-pghistory
"allauth",
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.google",
"allauth.socialaccount.providers.discord",
"django_cleanup",
"django_filters",
"django_htmx",
"whitenoise",
"django_tailwind_cli",
"autocomplete", # Django HTMX Autocomplete
"debug_toolbar",
"silk",
"apps.core",
"apps.accounts",
"apps.parks",
"apps.rides",
"apps.email_service",
"apps.media.apps.MediaConfig",
"apps.moderation",
"apps.location",
]
MIDDLEWARE = [
"django.middleware.cache.UpdateCacheMiddleware",
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"debug_toolbar.middleware.DebugToolbarMiddleware",
"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",
"apps.core.middleware.PgHistoryContextMiddleware", # Add history context tracking
"allauth.account.middleware.AccountMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
"django_htmx.middleware.HtmxMiddleware",
"apps.core.middleware.view_tracking.ViewTrackingMiddleware", # Add our page view tracking
]
ROOT_URLCONF = "thrillwiki.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(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",
"apps.moderation.context_processors.moderation_access",
]
},
}
]
WSGI_APPLICATION = "thrillwiki.wsgi.application"
# Database
# For development, use PostgreSQL with PostGIS for GeoDjango features
DATABASES = {
"default": {
"ENGINE": "django.contrib.gis.db.backends.postgis",
"NAME": "thrillwiki",
"USER": "postgres",
"PASSWORD": "postgres",
"HOST": "localhost",
"PORT": "5432",
}
}
# Cache settings
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
"TIMEOUT": 300, # 5 minutes
}
}
# Redis settings for trending cache
REDIS_URL = "redis://127.0.0.1:6379/0"
CACHE_MIDDLEWARE_SECONDS = 1 # 5 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = "thrillwiki"
# Password validation
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
LANGUAGE_CODE = "en-us"
TIME_ZONE = "America/New_York"
USE_I18N = True
USE_TZ = True
# Static files (CSS JavaScript Images)
STATIC_URL = "static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
# Media files - point to shared/media directory
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR.parent, "shared", "media")
# Default primary key field type
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Authentication settings
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
]
# django-allauth settings
SITE_ID = 1
ACCOUNT_SIGNUP_FIELDS = ["email*", "username*", "password1*", "password2*"]
ACCOUNT_LOGIN_METHODS = {"email", "username"}
ACCOUNT_EMAIL_VERIFICATION = "optional"
LOGIN_REDIRECT_URL = "/"
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
# Custom adapters
ACCOUNT_ADAPTER = "apps.accounts.adapters.CustomAccountAdapter"
SOCIALACCOUNT_ADAPTER = "apps.accounts.adapters.CustomSocialAccountAdapter"
# Social account settings
# OAuth provider configuration moved to database SocialApp objects
# This prevents conflicts between settings-based and database-based
# configurations
SOCIALACCOUNT_PROVIDERS = {
"google": {
"SCOPE": [
"profile",
"email",
],
"AUTH_PARAMS": {"access_type": "online"},
},
"discord": {
"SCOPE": ["identify", "email"],
"OAUTH_PKCE_ENABLED": True,
},
}
# Additional social account settings
SOCIALACCOUNT_LOGIN_ON_GET = True
SOCIALACCOUNT_AUTO_SIGNUP = False
SOCIALACCOUNT_STORE_TOKENS = True
# Email settings
EMAIL_BACKEND = "apps.email_service.backends.ForwardEmailBackend"
FORWARD_EMAIL_BASE_URL = "https://api.forwardemail.net"
SERVER_EMAIL = "django_webmaster@thrillwiki.com"
# Custom User Model
AUTH_USER_MODEL = "accounts.User"
# Autocomplete configuration
# Enable project-wide authentication requirement for autocomplete
AUTOCOMPLETE_BLOCK_UNAUTHENTICATED = False
# Tailwind configuration
# Tailwind configuration
TAILWIND_CLI_CONFIG_FILE = os.path.join(BASE_DIR, "tailwind.config.js")
TAILWIND_CLI_SRC_CSS = os.path.join(BASE_DIR, "static/css/src/input.css")
TAILWIND_CLI_DIST_CSS = os.path.join(BASE_DIR, "static/css/tailwind.css")
# Cloudflare Turnstile settings
TURNSTILE_SITE_KEY = "0x4AAAAAAAyqVp3RjccrC9Kz"
TURNSTILE_SECRET_KEY = "0x4AAAAAAAyqVrQolYsrAFGJ39PXHJ_HQzY"
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
# Test runner
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# Road Trip Service Settings
ROADTRIP_CACHE_TIMEOUT = 3600 * 24 # 24 hours for geocoding
ROADTRIP_ROUTE_CACHE_TIMEOUT = 3600 * 6 # 6 hours for routes
ROADTRIP_MAX_REQUESTS_PER_SECOND = 1 # Respect OSM rate limits
ROADTRIP_USER_AGENT = "ThrillWiki Road Trip Planner (https://thrillwiki.com)"
ROADTRIP_REQUEST_TIMEOUT = 10 # seconds
ROADTRIP_MAX_RETRIES = 3
ROADTRIP_BACKOFF_FACTOR = 2
# Debug Toolbar Configuration
INTERNAL_IPS = [
"127.0.0.1",
"localhost",
]

View File

@@ -6,9 +6,14 @@ from apps.parks.models import Park, Company
from apps.rides.models import Ride
from apps.core.analytics import PageView
from django.conf import settings
import logging
import os
import secrets
from apps.core.logging import log_exception
logger = logging.getLogger(__name__)
def handler404(request, exception):
return render(request, "404.html", status=404)
@@ -50,7 +55,13 @@ class HomeView(TemplateView):
trending_parks = Park.objects.exclude(
average_rating__isnull=True
).order_by("-average_rating")[:10]
except Exception:
except Exception as e:
log_exception(
logger,
e,
context={"operation": "get_trending_parks", "fallback": True},
request=self.request,
)
# Fallback to highest rated parks if trending calculation fails
trending_parks = Park.objects.exclude(
average_rating__isnull=True
@@ -70,7 +81,13 @@ class HomeView(TemplateView):
trending_rides = Ride.objects.exclude(
average_rating__isnull=True
).order_by("-average_rating")[:10]
except Exception:
except Exception as e:
log_exception(
logger,
e,
context={"operation": "get_trending_rides", "fallback": True},
request=self.request,
)
# Fallback to highest rated rides if trending calculation fails
trending_rides = Ride.objects.exclude(
average_rating__isnull=True
@@ -137,6 +154,22 @@ class SearchView(TemplateView):
Q(name__icontains=query) | Q(description__icontains=query)
).prefetch_related("operated_parks", "owned_parks")[:10]
logger.info(
f"Search query: '{query}' returned {len(context['parks'])} parks, "
f"{len(context['rides'])} rides, {len(context['companies'])} companies",
extra={
"query": query,
"parks_count": len(context["parks"]),
"rides_count": len(context["rides"]),
"companies_count": len(context["companies"]),
"user_id": (
self.request.user.id
if self.request.user.is_authenticated
else None
),
},
)
return context

View File

@@ -5,12 +5,18 @@ It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
This module is used for production deployments with WSGI servers like Gunicorn.
The settings module defaults to production, but can be overridden via the
DJANGO_SETTINGS_MODULE environment variable.
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.django.base")
# Default to production settings for WSGI deployments
# This can be overridden by setting DJANGO_SETTINGS_MODULE environment variable
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.django.production")
application = get_wsgi_application()