-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings.py
More file actions
445 lines (380 loc) · 14.6 KB
/
Copy pathsettings.py
File metadata and controls
445 lines (380 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 6.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""
import os
from datetime import timedelta
from pathlib import Path
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# IS_PRODUCTION covers both Render and self-hosted Docker deployments.
IS_PRODUCTION = bool(os.environ.get("PRODUCTION", ""))
# SECURITY WARNING: keep the secret key used in production secret!
if IS_PRODUCTION:
SECRET_KEY = os.environ["SECRET_KEY"]
else:
SECRET_KEY = os.environ.get(
"SECRET_KEY",
"django-insecure-$jk-$#)vf5(ui&x2=atf+lj(zy6pxcu*ia7%z$kersf*7yrx%",
)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = not IS_PRODUCTION
ADMIN_URL = os.environ.get("ADMIN_URL", "admin")
ADMIN_INGRESS_HOST = os.environ.get("ADMIN_INGRESS_HOST", "")
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]
# ALLOWED_HOSTS: comma-separated hostnames (e.g. "potterdoc.com,www.potterdoc.com")
_ALLOWED_HOSTS_ENV = os.environ.get("ALLOWED_HOSTS", os.environ.get("ALLOWED_HOST", ""))
def _shared_cookie_domain(host: str) -> str | None:
host = host.strip()
if not host:
return None
if host.startswith("www."):
host = host.removeprefix("www.")
if "." not in host or host == "localhost":
return None
return f".{host}"
def _add_allowed_host(host: str, *, allow_www: bool) -> None:
host = host.strip()
if not host:
return
ALLOWED_HOSTS.append(host)
# Automatically allow 'www.' only for the main public host.
if allow_www and "." in host and not host.startswith("www."):
ALLOWED_HOSTS.append(f"www.{host}")
if _ALLOWED_HOSTS_ENV:
for host in _ALLOWED_HOSTS_ENV.split(","):
_add_allowed_host(host, allow_www=True)
if ADMIN_INGRESS_HOST:
_add_allowed_host(ADMIN_INGRESS_HOST, allow_www=False)
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGIN_REGEXES = [
# match localhost with any port
r"^http:\/\/localhost:*([0-9]+)?$",
r"^https:\/\/localhost:*([0-9]+)?$",
]
CSRF_TRUSTED_ORIGINS = []
CORS_ALLOWED_ORIGINS = []
# APP_ORIGIN: full origin URL for self-hosted deployments (e.g. https://myapp.example.com)
_APP_ORIGIN = os.environ.get("APP_ORIGIN", "")
if _APP_ORIGIN:
CORS_ALLOWED_ORIGINS.append(_APP_ORIGIN)
CSRF_TRUSTED_ORIGINS.append(_APP_ORIGIN)
_COOKIE_DOMAIN = _shared_cookie_domain(
_ALLOWED_HOSTS_ENV.split(",")[0]
if _ALLOWED_HOSTS_ENV
else os.environ.get("ALLOWED_HOST", "")
)
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.humanize",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"adminsortable2",
"import_export",
"meta",
"rest_framework",
"corsheaders",
"drf_spectacular",
"helpdesk.apps.HelpdeskConfig",
"rest_framework_simplejwt.token_blacklist",
"api",
]
HELPDESK_TEAMS_MODE_ENABLED = False
REST_FRAMEWORK = {
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
"DEFAULT_AUTHENTICATION_CLASSES": [
"api.auth.agent_auth.AgentTokenAuthentication",
"api.auth.jwt_auth.JWTCookieAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
],
# One nginx reverse proxy sits in front of the app; tell DRF to trust
# exactly one layer of X-Forwarded-For so throttle keys use the real
# client IP rather than the proxy's address or a spoofed header value.
"NUM_PROXIES": 1,
# Scoped throttle rates. Applied only by views that opt in via a
# throttle class with a matching scope (e.g. the email-invite send
# endpoint); there is no global default throttle.
"DEFAULT_THROTTLE_RATES": {
"invite_send": "60/hour",
# Anonymous write proxy — 100 bursts per minute per IP is generous for
# legitimate SDK usage while still blocking trivial flood attacks.
"browser_traces": "100/min",
# Google OAuth initiation — keeps bot-driven sign-in floods cheap to
# block without impacting normal login UX (users rarely retry > once).
"google_auth": "10/min",
},
}
SIMPLE_JWT = {
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=15),
"REFRESH_TOKEN_LIFETIME": timedelta(days=30),
"SIGNING_KEY": SECRET_KEY,
"AUTH_HEADER_TYPES": ("Bearer",),
}
def openapi_preprocessing_filter_spec(endpoints):
filtered = []
for path, path_regex, method, callback in endpoints:
if path.startswith("/api/"):
filtered.append((path, path_regex, method, callback))
return filtered
SPECTACULAR_SETTINGS = {
"TITLE": "PotterDoc API",
"DESCRIPTION": (
"Pottery workflow tracking API.\n\n"
"**Authentication:** Protected endpoints accept either a session cookie or "
"a Bearer access token. To authenticate in this UI, click **Authorize** and "
"paste the value of your `sessionid` cookie or an `accessToken` returned by "
"`POST /api/auth/token/`."
),
"VERSION": "0.0.1",
"SECURITY": [{"cookieAuth": []}, {"bearerAuth": []}],
"COMPONENTS": {
"securitySchemes": {
"cookieAuth": {
"type": "apiKey",
"in": "cookie",
"name": "sessionid",
"description": (
"Django session cookie. Log in via the web UI, then copy the "
"`sessionid` value from DevTools → Application → Cookies."
),
},
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": (
"Bearer access token returned by `POST /api/auth/token/` or "
"`POST /api/auth/token/refresh/`."
),
},
}
},
"PREPROCESSING_HOOKS": ["backend.settings.openapi_preprocessing_filter_spec"],
}
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
# WhiteNoise must come directly after SecurityMiddleware and before all others.
# AsyncCompatWhiteNoiseMiddleware wraps the sync file iterator in an async
# generator so Django's ASGI handler never sees a bare map() object.
"backend.middleware.AsyncCompatWhiteNoiseMiddleware",
"corsheaders.middleware.CorsMiddleware",
"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 = "backend.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "backend.wsgi.application"
ASGI_APPLICATION = "backend.asgi.application"
# Production sits behind Nginx, which terminates TLS and proxies to Gunicorn over
# plain HTTP. Trust only the proxy's X-Forwarded-Proto value so Django still
# treats external HTTPS requests as secure.
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
USE_X_FORWARDED_HOST = False
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
#
# On Render, DATABASE_URL is provided automatically when a Postgres database is
# attached to the web service.
if IS_PRODUCTION:
DATABASES = {
"default": dj_database_url.config(
conn_max_age=600,
conn_health_checks=True,
)
}
DATABASES["default"].setdefault("OPTIONS", {})["options"] = "-c timezone=UTC"
elif os.environ.get("DATABASE_URL"):
DATABASES = {"default": dj_database_url.config(conn_max_age=60)}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": str(BASE_DIR / "db.sqlite3"),
}
}
# Enable native connection pooling for PostgreSQL
if DATABASES.get("default", {}).get("ENGINE") == "django.db.backends.postgresql":
DATABASES["default"].setdefault("OPTIONS", {})["pool"] = True
DATABASES["default"]["CONN_MAX_AGE"] = 0
# Password validation
# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = []
# Internationalization
# https://docs.djangoproject.com/en/6.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
#
# STATIC_ROOT / STATIC_URL: Django admin CSS, DRF browsable API assets, etc.
# WHITENOISE_ROOT: serves the Vite-built React SPA at the URL root (no /static/
# prefix), so hardcoded paths like /thumbnails/... work without change.
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
# Serve the Vite production build at the URL root when it exists.
# WHITENOISE_ROOT lets WhiteNoise serve web/dist at / (no /static/ prefix),
# so asset paths like /thumbnails/... embedded in index.html work unchanged.
# STATICFILES_DIRS ensures collectstatic copies and compresses these files too.
_WEB_DIST = BASE_DIR / "web" / "dist"
if _WEB_DIST.is_dir():
WHITENOISE_ROOT = _WEB_DIST
STATICFILES_DIRS = [_WEB_DIST]
STORAGES = {
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
"staticfiles": {
# Compress files but do not re-hash; Vite already adds content hashes
# to its output filenames, so a second hash layer would break the URLs
# embedded in index.html.
"BACKEND": "whitenoise.storage.CompressedStaticFilesStorage",
},
}
# Default primary key field type
# https://docs.djangoproject.com/en/6.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
# Google OAuth — set GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET in the environment.
GOOGLE_OAUTH_CLIENT_ID = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
GOOGLE_OAUTH_CLIENT_SECRET = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "")
# Development bootstrap helpers. Enabled by default in DEBUG to make freshly
# created local worktrees usable immediately after first login, but fully
# disabled in production.
DEV_BOOTSTRAP_ENABLED = (
DEBUG and os.environ.get("GLAZE_DEV_BOOTSTRAP", "1") == "1"
) or (os.environ.get("GLAZE_DEV_BOOTSTRAP") == "force")
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(levelname)s %(asctime)s %(name)s [trace=%(trace_id)s] %(message)s",
},
},
"filters": {
"otel_trace": {
"()": "api.logging.OtelTraceFilter",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "console",
"filters": ["otel_trace"],
},
},
"root": {
"handlers": ["console"],
"level": "INFO",
},
"loggers": {
"django": {
"handlers": ["console"],
"level": "INFO",
"propagate": True,
},
"django.request": {
"handlers": ["console"],
"level": "INFO",
"propagate": False,
},
"api": {
"handlers": ["console"],
"level": "INFO",
"propagate": False,
},
},
}
# Security settings
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin-allow-popups"
CSRF_COOKIE_NAME = "potterdoc_csrftoken"
if IS_PRODUCTION:
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_SSL_REDIRECT = True
SECURE_REDIRECT_EXEMPT = [r"^api/health/"]
if _COOKIE_DOMAIN:
SESSION_COOKIE_DOMAIN = _COOKIE_DOMAIN
# Remote ML Offloading (Modal)
REMOTE_REMBG_URL = os.environ.get("REMOTE_REMBG_URL", "")
MODAL_AUTH_TOKEN = os.environ.get("MODAL_AUTH_TOKEN", "")
# Email — production uses Resend SMTP; dev defaults to console (prints to stdout).
# To preview rendered emails locally: docker compose --profile mail up -d mailpit
# then set EMAIL_HOST=localhost EMAIL_PORT=1025 EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
# Mailpit web UI: http://localhost:8025
DEFAULT_FROM_EMAIL = os.environ.get("DEFAULT_FROM_EMAIL", "noreply@potterdoc.com")
INVITE_LINK_BASE_URL = os.environ.get("INVITE_LINK_BASE_URL", "http://localhost:5173")
if IS_PRODUCTION:
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = os.environ.get("EMAIL_HOST", "smtp.resend.com")
EMAIL_PORT = int(os.environ.get("EMAIL_PORT", "465"))
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "resend")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_SSL = os.environ.get("EMAIL_USE_SSL", "true").lower() == "true"
else:
EMAIL_BACKEND = os.environ.get(
"EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend"
)
EMAIL_HOST = os.environ.get("EMAIL_HOST", "localhost")
EMAIL_PORT = int(os.environ.get("EMAIL_PORT", "1025"))
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_SSL = False
# Caching
# https://docs.djangoproject.com/en/6.0/ref/settings/#caches
#
# Use shared Redis cache in production if REDIS_CACHE_URL is provided.
# Falls back to DummyCache to prevent accidental reliance on LocMemCache (per-process).
REDIS_CACHE_URL = os.environ.get("REDIS_CACHE_URL", "")
if REDIS_CACHE_URL:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": REDIS_CACHE_URL,
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}
else:
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.dummy.DummyCache",
}
}
if REDIS_CACHE_URL:
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"