Add comprehensive tests for Parks API and models

- Implemented extensive test cases for the Parks API, covering endpoints for listing, retrieving, creating, updating, and deleting parks.
- Added tests for filtering, searching, and ordering parks in the API.
- Created tests for error handling in the API, including malformed JSON and unsupported methods.
- Developed model tests for Park, ParkArea, Company, and ParkReview models, ensuring validation and constraints are enforced.
- Introduced utility mixins for API and model testing to streamline assertions and enhance test readability.
- Included integration tests to validate complete workflows involving park creation, retrieval, updating, and deletion.
This commit is contained in:
pacnpal
2025-08-17 19:36:20 -04:00
parent 17228e9935
commit c26414ff74
210 changed files with 24155 additions and 833 deletions

2
config/__init__.py Normal file
View File

@@ -0,0 +1,2 @@
# Configuration package for thrillwiki project

View File

@@ -0,0 +1,2 @@
# Django settings package

370
config/django/base.py Normal file
View File

@@ -0,0 +1,370 @@
"""
Base Django settings for thrillwiki project.
Common settings shared across all environments.
"""
import os
import environ
from pathlib import Path
# Initialize environment variables
env = environ.Env(
DEBUG=(bool, False),
SECRET_KEY=(str, ''),
ALLOWED_HOSTS=(list, []),
DATABASE_URL=(str, ''),
CACHE_URL=(str, 'locmem://'),
EMAIL_URL=(str, ''),
REDIS_URL=(str, ''),
)
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Read environment file if it exists
environ.Env.read_env(BASE_DIR / '***REMOVED***')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')
# Allowed hosts
ALLOWED_HOSTS = env('ALLOWED_HOSTS')
# CSRF trusted origins
CSRF_TRUSTED_ORIGINS = env('CSRF_TRUSTED_ORIGINS', default=[])
# Application definition
DJANGO_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", # GeoDjango
]
THIRD_PARTY_APPS = [
"rest_framework", # Django REST Framework
"drf_spectacular", # OpenAPI 3.0 documentation
"corsheaders", # CORS headers for API
"pghistory", # 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
"health_check", # Health checks
"health_check.db",
"health_check.cache",
"health_check.storage",
"health_check.contrib.migrations",
"health_check.contrib.redis",
]
LOCAL_APPS = [
"core",
"accounts",
"parks",
"rides",
"email_service",
"media.apps.MediaConfig",
"moderation",
"location",
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
"django.middleware.cache.UpdateCacheMiddleware",
"corsheaders.middleware.CorsMiddleware", # CORS middleware for API
"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",
"core.middleware.PgHistoryContextMiddleware", # Add history context tracking
"allauth.account.middleware.AccountMiddleware",
"django.middleware.cache.FetchFromCacheMiddleware",
"django_htmx.middleware.HtmxMiddleware",
"core.middleware.PageViewMiddleware", # Add our page view tracking
]
ROOT_URLCONF = "thrillwiki.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",
"moderation.context_processors.moderation_access",
]
}
}
]
WSGI_APPLICATION = "thrillwiki.wsgi.application"
# 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 = BASE_DIR / "staticfiles"
# Media files
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "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 = "accounts.adapters.CustomAccountAdapter"
SOCIALACCOUNT_ADAPTER = "accounts.adapters.CustomSocialAccountAdapter"
# Social account settings
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
# Custom User Model
AUTH_USER_MODEL = "accounts.User"
# Autocomplete configuration
AUTOCOMPLETE_BLOCK_UNAUTHENTICATED = False
# Tailwind configuration
TAILWIND_CLI_CONFIG_FILE = BASE_DIR / "tailwind.config.js"
TAILWIND_CLI_SRC_CSS = BASE_DIR / "static/css/src/input.css"
TAILWIND_CLI_DIST_CSS = BASE_DIR / "static/css/tailwind.css"
# 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
# Django REST Framework Settings
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',
'DEFAULT_VERSION': 'v1',
'ALLOWED_VERSIONS': ['v1'],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
],
'EXCEPTION_HANDLER': 'core.api.exceptions.custom_exception_handler',
'DEFAULT_FILTER_BACKENDS': [
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.SearchFilter',
'rest_framework.filters.OrderingFilter',
],
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'NON_FIELD_ERRORS_KEY': 'non_field_errors',
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
# CORS Settings for API
CORS_ALLOWED_ORIGINS = env('CORS_ALLOWED_ORIGINS', default=[])
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = env('CORS_ALLOW_ALL_ORIGINS', default=False)
# API-specific settings
API_RATE_LIMIT_PER_MINUTE = env.int('API_RATE_LIMIT_PER_MINUTE', default=60)
API_RATE_LIMIT_PER_HOUR = env.int('API_RATE_LIMIT_PER_HOUR', default=1000)
# drf-spectacular settings
SPECTACULAR_SETTINGS = {
'TITLE': 'ThrillWiki API',
'DESCRIPTION': 'Comprehensive theme park and ride information API',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
'COMPONENT_SPLIT_REQUEST': True,
'TAGS': [
{'name': 'parks', 'description': 'Theme park operations'},
{'name': 'rides', 'description': 'Ride information and management'},
{'name': 'locations', 'description': 'Geographic location services'},
{'name': 'accounts', 'description': 'User account management'},
{'name': 'media', 'description': 'Media and image management'},
{'name': 'moderation', 'description': 'Content moderation'},
],
'SCHEMA_PATH_PREFIX': '/api/',
'DEFAULT_GENERATOR_CLASS': 'drf_spectacular.generators.SchemaGenerator',
'SERVE_PERMISSIONS': ['rest_framework.permissions.AllowAny'],
'SWAGGER_UI_SETTINGS': {
'deepLinking': True,
'persistAuthorization': True,
'displayOperationId': False,
'displayRequestDuration': True,
},
'REDOC_UI_SETTINGS': {
'hideDownloadButton': False,
'hideHostname': False,
'hideLoading': False,
'hideSchemaPattern': True,
'scrollYOffset': 0,
'theme': {
'colors': {
'primary': {
'main': '#1976d2'
}
}
}
}
}
# Health Check Configuration
HEALTH_CHECK = {
'DISK_USAGE_MAX': 90, # Fail if disk usage is over 90%
'MEMORY_MIN': 100, # Fail if less than 100MB available memory
}
# Custom health check backends
HEALTH_CHECK_BACKENDS = [
'health_check.db',
'health_check.cache',
'health_check.storage',
'core.health_checks.custom_checks.CacheHealthCheck',
'core.health_checks.custom_checks.DatabasePerformanceCheck',
'core.health_checks.custom_checks.ApplicationHealthCheck',
'core.health_checks.custom_checks.ExternalServiceHealthCheck',
'core.health_checks.custom_checks.DiskSpaceHealthCheck',
]
# Enhanced Cache Configuration
DJANGO_REDIS_CACHE_BACKEND = 'django_redis.cache.RedisCache'
DJANGO_REDIS_CLIENT_CLASS = 'django_redis.client.DefaultClient'
CACHES = {
'default': {
'BACKEND': DJANGO_REDIS_CACHE_BACKEND,
'LOCATION': env('REDIS_URL', default='redis://127.0.0.1:6379/1'),
'OPTIONS': {
'CLIENT_CLASS': DJANGO_REDIS_CLIENT_CLASS,
'PARSER_CLASS': 'redis.connection.HiredisParser',
'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
'CONNECTION_POOL_CLASS_KWARGS': {
'max_connections': 50,
'timeout': 20,
},
'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor',
'IGNORE_EXCEPTIONS': True,
},
'KEY_PREFIX': 'thrillwiki',
'VERSION': 1,
},
'sessions': {
'BACKEND': DJANGO_REDIS_CACHE_BACKEND,
'LOCATION': env('REDIS_URL', default='redis://127.0.0.1:6379/2'),
'OPTIONS': {
'CLIENT_CLASS': DJANGO_REDIS_CLIENT_CLASS,
}
},
'api': {
'BACKEND': DJANGO_REDIS_CACHE_BACKEND,
'LOCATION': env('REDIS_URL', default='redis://127.0.0.1:6379/3'),
'OPTIONS': {
'CLIENT_CLASS': DJANGO_REDIS_CLIENT_CLASS,
}
}
}
# Use Redis for sessions
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'sessions'
SESSION_COOKIE_AGE = 86400 # 24 hours
# Cache middleware settings
CACHE_MIDDLEWARE_SECONDS = 300 # 5 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'thrillwiki'

176
config/django/local.py Normal file
View File

@@ -0,0 +1,176 @@
"""
Local development settings for thrillwiki project.
"""
from .base import *
from ..settings import database
from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST
from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS
from .base import env # Import env for environment variable access
# Development-specific settings
DEBUG = True
# For local development, allow all hosts
ALLOWED_HOSTS = ['*']
# CSRF trusted origins for local development
CSRF_TRUSTED_ORIGINS = [
"http://localhost:8000",
"http://127.0.0.1:8000",
"https://beta.thrillwiki.com",
]
# GeoDjango Settings for macOS development
GDAL_LIBRARY_PATH = env('GDAL_LIBRARY_PATH', default="/opt/homebrew/lib/libgdal.dylib")
GEOS_LIBRARY_PATH = env('GEOS_LIBRARY_PATH', default="/opt/homebrew/lib/libgeos_c.dylib")
# Local cache configuration
LOC_MEM_CACHE_BACKEND = "django.core.cache.backends.locmem.LocMemCache"
CACHES = {
"default": {
"BACKEND": LOC_MEM_CACHE_BACKEND,
"LOCATION": "unique-snowflake",
"TIMEOUT": 300, # 5 minutes
"OPTIONS": {"MAX_ENTRIES": 1000},
},
"sessions": {
"BACKEND": LOC_MEM_CACHE_BACKEND,
"LOCATION": "sessions-cache",
"TIMEOUT": 86400, # 24 hours (same as SESSION_COOKIE_AGE)
"OPTIONS": {"MAX_ENTRIES": 5000},
},
"api": {
"BACKEND": LOC_MEM_CACHE_BACKEND,
"LOCATION": "api-cache",
"TIMEOUT": 300, # 5 minutes
"OPTIONS": {"MAX_ENTRIES": 2000},
}
}
# Development-friendly cache settings
CACHE_MIDDLEWARE_SECONDS = 1 # Very short cache for development
CACHE_MIDDLEWARE_KEY_PREFIX = "thrillwiki_dev"
# Development email backend
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
# Security settings for development
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
# Development monitoring tools
DEVELOPMENT_APPS = [
'silk',
'debug_toolbar',
'nplusone.ext.django',
]
# Add development apps if available
for app in DEVELOPMENT_APPS:
if app not in INSTALLED_APPS:
INSTALLED_APPS.append(app)
# Development middleware
DEVELOPMENT_MIDDLEWARE = [
'silk.middleware.SilkyMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'nplusone.ext.django.NPlusOneMiddleware',
'core.middleware.performance_middleware.PerformanceMiddleware',
'core.middleware.performance_middleware.QueryCountMiddleware',
]
# Add development middleware
for middleware in DEVELOPMENT_MIDDLEWARE:
if middleware not in MIDDLEWARE:
MIDDLEWARE.insert(1, middleware) # Insert after security middleware
# Debug toolbar configuration
INTERNAL_IPS = ['127.0.0.1', '::1']
# Silk configuration for development
SILKY_PYTHON_PROFILER = True
SILKY_PYTHON_PROFILER_BINARY = True
SILKY_PYTHON_PROFILER_RESULT_PATH = BASE_DIR / 'profiles'
SILKY_AUTHENTICATION = True
SILKY_AUTHORISATION = True
# NPlusOne configuration
import logging
NPLUSONE_LOGGER = logging.getLogger('nplusone')
NPLUSONE_LOG_LEVEL = logging.WARN
# Enhanced development logging
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'json': {
'()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': BASE_DIR / 'logs' / 'thrillwiki.log',
'maxBytes': 1024*1024*10, # 10MB
'backupCount': 5,
'formatter': 'json',
},
'performance': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': BASE_DIR / 'logs' / 'performance.log',
'maxBytes': 1024*1024*10, # 10MB
'backupCount': 5,
'formatter': 'json',
},
},
'root': {
'level': 'INFO',
'handlers': ['console'],
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': False,
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'thrillwiki': {
'handlers': ['console', 'file'],
'level': 'DEBUG',
'propagate': False,
},
'performance': {
'handlers': ['performance'],
'level': 'INFO',
'propagate': False,
},
'query_optimization': {
'handlers': ['console', 'file'],
'level': 'WARNING',
'propagate': False,
},
'nplusone': {
'handlers': ['console'],
'level': 'WARNING',
'propagate': False,
},
},
}

View File

@@ -0,0 +1,97 @@
"""
Production settings for thrillwiki project.
"""
from . import base # Import the module and use its members, e.g., base.BASE_DIR, base***REMOVED***
from ..settings import database # Import the module and use its members, e.g., database.DATABASES
from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST
from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS
from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST
from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS
# Production settings
DEBUG = False
# Allowed hosts must be explicitly set in production
ALLOWED_HOSTS = base***REMOVED***('ALLOWED_HOSTS')
# CSRF trusted origins for production
CSRF_TRUSTED_ORIGINS = base***REMOVED***('CSRF_TRUSTED_ORIGINS', default=[])
# Security settings for production
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
# Production logging
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.handlers.RotatingFileHandler',
'filename': base.BASE_DIR / 'logs' / 'django.log',
'maxBytes': 1024*1024*15, # 15MB
'backupCount': 10,
'formatter': 'verbose',
},
'error_file': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': base.BASE_DIR / 'logs' / 'django_error.log',
'maxBytes': 1024*1024*15, # 15MB
'backupCount': 10,
'formatter': 'verbose',
},
},
'root': {
'handlers': ['file'],
'level': 'INFO',
},
'loggers': {
'django': {
'handlers': ['file', 'error_file'],
'level': 'INFO',
'propagate': False,
},
'thrillwiki': {
'handlers': ['file', 'error_file'],
'level': 'INFO',
'propagate': False,
},
},
}
# Static files collection for production
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Cache settings for production (Redis recommended)
if base***REMOVED***('REDIS_URL', default=None):
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': base***REMOVED***('REDIS_URL'),
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
# Use Redis for sessions in production
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_CACHE_ALIAS = 'default'

65
config/django/test.py Normal file
View File

@@ -0,0 +1,65 @@
"""
Test settings for thrillwiki project.
"""
from .base import *
# Test-specific settings
DEBUG = False
# Use in-memory database for faster tests
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.spatialite',
'NAME': ':memory:',
}
}
# Use in-memory cache for tests
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'test-cache',
}
}
# Disable migrations for faster tests
class DisableMigrations:
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
# Email backend for tests
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
# Password hashers for faster tests
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
# Disable logging during tests
LOGGING_CONFIG = None
# Media files for tests
MEDIA_ROOT = BASE_DIR / 'test_media'
# Static files for tests
STATIC_ROOT = BASE_DIR / 'test_static'
# Disable Turnstile for tests
TURNSTILE_SITE_KEY = 'test-key'
TURNSTILE_SECRET_KEY = 'test-secret'
# Test-specific middleware (remove caching middleware)
MIDDLEWARE = [m for m in MIDDLEWARE if 'cache' not in m.lower()]
# Celery settings for tests (if Celery is used)
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True

View File

@@ -0,0 +1,46 @@
"""
Test Django settings for thrillwiki accounts app.
"""
from .base import *
# Use in-memory database for tests
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'test_db',
}
}
# Use a faster password hasher for tests
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
# Disable whitenoise for tests
WHITENOISE_AUTOREFRESH = True
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"django.contrib.sites",
"allauth",
"allauth.account",
"allauth.socialaccount",
"accounts",
"core",
"pghistory",
"pgtrigger",
"email_service",
"parks",
"rides",
"media.apps.MediaConfig",
]
GDAL_LIBRARY_PATH = '/opt/homebrew/lib/libgdal.dylib'
GEOS_LIBRARY_PATH = '/opt/homebrew/lib/libgeos_c.dylib'

View File

@@ -0,0 +1,2 @@
# Settings modules package

View File

@@ -0,0 +1,25 @@
"""
Database configuration for thrillwiki project.
"""
import environ
env = environ.Env()
# Database configuration
DATABASES = {
'default': env.db(),
}
# GeoDjango Settings - Environment specific
GDAL_LIBRARY_PATH = env('GDAL_LIBRARY_PATH', default=None)
GEOS_LIBRARY_PATH = env('GEOS_LIBRARY_PATH', default=None)
# Cache settings
CACHES = {
'default': env.cache('CACHE_URL', default='locmemcache://')
}
CACHE_MIDDLEWARE_SECONDS = env.int('CACHE_MIDDLEWARE_SECONDS', default=300) # 5 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = env('CACHE_MIDDLEWARE_KEY_PREFIX', default='thrillwiki')

19
config/settings/email.py Normal file
View File

@@ -0,0 +1,19 @@
"""
Email configuration for thrillwiki project.
"""
import environ
env = environ.Env()
# Email settings
EMAIL_BACKEND = env('EMAIL_BACKEND', default='email_service.backends.ForwardEmailBackend')
FORWARD_EMAIL_BASE_URL = env('FORWARD_EMAIL_BASE_URL', default='https://api.forwardemail.net')
SERVER_EMAIL = env('SERVER_EMAIL', default='django_webmaster@thrillwiki.com')
# Email URLs can be configured using EMAIL_URL environment variable
# Example: EMAIL_URL=smtp://user:pass@localhost:587
if env('EMAIL_URL', default=None):
email_config = env.email_url()
vars().update(email_config)

View File

@@ -0,0 +1,32 @@
"""
Security configuration for thrillwiki project.
"""
import environ
env = environ.Env()
# Cloudflare Turnstile settings
TURNSTILE_SITE_KEY = env('TURNSTILE_SITE_KEY', default='')
TURNSTILE_SECRET_KEY = env('TURNSTILE_SECRET_KEY', default='')
TURNSTILE_VERIFY_URL = env('TURNSTILE_VERIFY_URL', default='https://challenges.cloudflare.com/turnstile/v0/siteverify')
# Security headers and settings (for production)
SECURE_BROWSER_XSS_FILTER = env.bool('SECURE_BROWSER_XSS_FILTER', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool('SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool('SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_HSTS_SECONDS = env.int('SECURE_HSTS_SECONDS', default=31536000) # 1 year
SECURE_REDIRECT_EXEMPT = env.list('SECURE_REDIRECT_EXEMPT', default=[])
SECURE_SSL_REDIRECT = env.bool('SECURE_SSL_REDIRECT', default=False)
SECURE_PROXY_SSL_HEADER = env.tuple('SECURE_PROXY_SSL_HEADER', default=None)
# Session security
SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', default=False)
SESSION_COOKIE_HTTPONLY = env.bool('SESSION_COOKIE_HTTPONLY', default=True)
SESSION_COOKIE_SAMESITE = env('SESSION_COOKIE_SAMESITE', default='Lax')
# CSRF security
CSRF_COOKIE_SECURE = env.bool('CSRF_COOKIE_SECURE', default=False)
CSRF_COOKIE_HTTPONLY = env.bool('CSRF_COOKIE_HTTPONLY', default=True)
CSRF_COOKIE_SAMESITE = env('CSRF_COOKIE_SAMESITE', default='Lax')