settings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. """
  2. Django settings for glitchtip project.
  3. Generated by 'django-admin startproject' using Django 3.0rc1.
  4. For more information on this file, see
  5. https://docs.djangoproject.com/en/dev/topics/settings/
  6. For the full list of settings and their values, see
  7. https://docs.djangoproject.com/en/dev/ref/settings/
  8. """
  9. import logging
  10. import os
  11. import sys
  12. import warnings
  13. from datetime import timedelta
  14. import environ
  15. import sentry_sdk
  16. from celery.schedules import crontab
  17. from corsheaders.defaults import default_headers
  18. from django.core.exceptions import ImproperlyConfigured
  19. from sentry_sdk.integrations.django import DjangoIntegration
  20. from whitenoise.storage import CompressedManifestStaticFilesStorage
  21. env = environ.Env(
  22. ALLOWED_HOSTS=(list, ["*"]),
  23. DEFAULT_FILE_STORAGE=(str, None),
  24. GS_BUCKET_NAME=(str, None),
  25. AWS_ACCESS_KEY_ID=(str, None),
  26. AWS_SECRET_ACCESS_KEY=(str, None),
  27. AWS_STORAGE_BUCKET_NAME=(str, None),
  28. AWS_S3_ENDPOINT_URL=(str, None),
  29. AWS_LOCATION=(str, ""),
  30. DEBUG=(bool, False),
  31. DEBUG_TOOLBAR=(bool, False),
  32. STATIC_URL=(str, "/"),
  33. STATICFILES_STORAGE=(
  34. str,
  35. "glitchtip.settings.NoSourceMapsStorage",
  36. ),
  37. ENABLE_OBSERVABILITY_API=(bool, False),
  38. )
  39. path = environ.Path()
  40. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  41. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  42. # Quick-start development settings - unsuitable for production
  43. # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
  44. # SECURITY WARNING: keep the secret key used in production secret!
  45. SECRET_KEY = env.str("SECRET_KEY", "change_me")
  46. # SECURITY WARNING: don't run with debug turned on in production!
  47. DEBUG = env("DEBUG")
  48. # Enable only for running end to end testing. Debug must be True to use.
  49. ENABLE_TEST_API = env.bool("ENABLE_TEST_API", False)
  50. if DEBUG is False:
  51. ENABLE_TEST_API = False
  52. ALLOWED_HOSTS = env("ALLOWED_HOSTS")
  53. # Necessary for kubernetes health checks
  54. POD_IP = env.str("POD_IP", default=None)
  55. if POD_IP:
  56. ALLOWED_HOSTS.append(POD_IP)
  57. ENVIRONMENT = env.str("ENVIRONMENT", None)
  58. GLITCHTIP_VERSION = env.str("GLITCHTIP_VERSION", "0.0.0-unknown")
  59. # Used in email and DSN generation. Set to full domain such as https://glitchtip.example.com
  60. default_url = env.str(
  61. "APP_URL", env.str("GLITCHTIP_DOMAIN", "http://localhost:8000")
  62. ) # DigitalOcean App Platform uses APP_URL
  63. GLITCHTIP_URL = env.url("GLITCHTIP_URL", default_url)
  64. if GLITCHTIP_URL.scheme not in ["http", "https"]:
  65. raise ImproperlyConfigured("GLITCHTIP_DOMAIN must start with http or https")
  66. # Events and associated data older than this will be deleted from the database
  67. GLITCHTIP_MAX_EVENT_LIFE_DAYS = env.int("GLITCHTIP_MAX_EVENT_LIFE_DAYS", default=90)
  68. # For development purposes only, prints out inbound event store json
  69. EVENT_STORE_DEBUG = env.bool("EVENT_STORE_DEBUG", False)
  70. # Throttle % of all transaction events. Not intended for general use. May change without warning.
  71. THROTTLE_TRANSACTION_EVENTS = env.float("THROTTLE_TRANSACTION_EVENTS", None)
  72. GLITCHTIP_ENABLE_DIFS = env.bool("GLITCHTIP_ENABLE_DIFS", False)
  73. # GlitchTip can track GlitchTip's own errors.
  74. # If enabling this, use a different server to avoid infinite loops.
  75. def before_send(event, hint):
  76. """Don't log django.DisallowedHost errors in Sentry."""
  77. if "log_record" in hint:
  78. if hint["log_record"].name == "django.security.DisallowedHost":
  79. return None
  80. return event
  81. SENTRY_DSN = env.str("SENTRY_DSN", None)
  82. # Optionally allow a different DSN for the frontend
  83. SENTRY_FRONTEND_DSN = env.str("SENTRY_FRONTEND_DSN", SENTRY_DSN)
  84. # Set traces_sample_rate to 1.0 to capture 100%. Recommended to keep this value low.
  85. # Disabled by default
  86. SENTRY_TRACES_SAMPLE_RATE = env.float("SENTRY_TRACES_SAMPLE_RATE", None)
  87. if SENTRY_DSN:
  88. release = "glitchtip@" + GLITCHTIP_VERSION if GLITCHTIP_VERSION else None
  89. sentry_sdk.init(
  90. dsn=SENTRY_DSN,
  91. integrations=[DjangoIntegration()],
  92. before_send=before_send,
  93. release=release,
  94. environment=ENVIRONMENT,
  95. auto_session_tracking=False,
  96. traces_sample_rate=SENTRY_TRACES_SAMPLE_RATE,
  97. )
  98. def show_toolbar(request):
  99. return env("DEBUG_TOOLBAR")
  100. DEBUG_TOOLBAR_CONFIG = {"SHOW_TOOLBAR_CALLBACK": show_toolbar}
  101. DEBUG_TOOLBAR_PANELS = [
  102. "debug_toolbar.panels.versions.VersionsPanel",
  103. "debug_toolbar.panels.timer.TimerPanel",
  104. "debug_toolbar.panels.settings.SettingsPanel",
  105. "debug_toolbar.panels.headers.HeadersPanel",
  106. "debug_toolbar.panels.request.RequestPanel",
  107. "debug_toolbar.panels.sql.SQLPanel",
  108. ]
  109. # Application definition
  110. INSTALLED_APPS = [
  111. "django_rest_mfa.mfa_admin",
  112. "django.contrib.admin",
  113. "django.contrib.auth",
  114. "django.contrib.contenttypes",
  115. "django.contrib.sessions",
  116. "django.contrib.messages",
  117. "django.contrib.staticfiles",
  118. "django.contrib.sites",
  119. "django.contrib.postgres",
  120. "django_prometheus",
  121. "allauth",
  122. "allauth.account",
  123. "allauth.socialaccount",
  124. "allauth.socialaccount.providers.digitalocean",
  125. "allauth.socialaccount.providers.gitea",
  126. "allauth.socialaccount.providers.github",
  127. "allauth.socialaccount.providers.gitlab",
  128. "allauth.socialaccount.providers.google",
  129. "allauth.socialaccount.providers.microsoft",
  130. "allauth.socialaccount.providers.nextcloud",
  131. "anymail",
  132. "corsheaders",
  133. "django_celery_results",
  134. "django_filters",
  135. "django_extensions",
  136. "django_rest_mfa",
  137. "debug_toolbar",
  138. "rest_framework",
  139. "drf_yasg",
  140. "dj_rest_auth",
  141. "dj_rest_auth.registration",
  142. "storages",
  143. "glitchtip",
  144. "alerts",
  145. "api_tokens",
  146. "environments",
  147. "files",
  148. "organizations_ext",
  149. "events",
  150. "issues",
  151. "users",
  152. "user_reports",
  153. "glitchtip.uptime",
  154. "performance",
  155. "projects",
  156. "teams",
  157. "releases",
  158. "difs",
  159. ]
  160. # Ensure no one uses runsslserver in production
  161. if SECRET_KEY == "change_me" and DEBUG is True:
  162. INSTALLED_APPS += ["sslserver"]
  163. ENABLE_OBSERVABILITY_API = env("ENABLE_OBSERVABILITY_API")
  164. # Workaround https://github.com/korfuri/django-prometheus/issues/34
  165. PROMETHEUS_EXPORT_MIGRATIONS = False
  166. MIDDLEWARE = [
  167. "django.middleware.security.SecurityMiddleware",
  168. "django.contrib.sessions.middleware.SessionMiddleware",
  169. "corsheaders.middleware.CorsMiddleware",
  170. "csp.middleware.CSPMiddleware",
  171. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  172. "whitenoise.middleware.WhiteNoiseMiddleware",
  173. "debug_toolbar.middleware.DebugToolbarMiddleware",
  174. "django.middleware.common.CommonMiddleware",
  175. "django.middleware.csrf.CsrfViewMiddleware",
  176. "django.contrib.auth.middleware.AuthenticationMiddleware",
  177. "django.contrib.messages.middleware.MessageMiddleware",
  178. "django.middleware.clickjacking.XFrameOptionsMiddleware",
  179. "sentry.middleware.proxy.DecompressBodyMiddleware",
  180. ]
  181. if ENABLE_OBSERVABILITY_API:
  182. MIDDLEWARE.insert(0, "django_prometheus.middleware.PrometheusBeforeMiddleware")
  183. MIDDLEWARE.append("django_prometheus.middleware.PrometheusAfterMiddleware")
  184. ROOT_URLCONF = "glitchtip.urls"
  185. TEMPLATES = [
  186. {
  187. "BACKEND": "django.template.backends.django.DjangoTemplates",
  188. "DIRS": [path("dist"), path("templates")],
  189. "APP_DIRS": True,
  190. "OPTIONS": {
  191. "context_processors": [
  192. "django.template.context_processors.debug",
  193. "django.template.context_processors.request",
  194. "django.contrib.auth.context_processors.auth",
  195. "django.contrib.messages.context_processors.messages",
  196. ],
  197. },
  198. },
  199. ]
  200. WSGI_APPLICATION = "glitchtip.wsgi.application"
  201. CORS_ORIGIN_ALLOW_ALL = env.bool("CORS_ORIGIN_ALLOW_ALL", True)
  202. CORS_ORIGIN_WHITELIST = env.tuple("CORS_ORIGIN_WHITELIST", str, default=())
  203. CORS_ALLOW_HEADERS = list(default_headers) + [
  204. "x-sentry-auth",
  205. ]
  206. SECURE_BROWSER_XSS_FILTER = True
  207. CSP_DEFAULT_SRC = env.list("CSP_DEFAULT_SRC", str, ["'self'"])
  208. CSP_STYLE_SRC = env.list(
  209. "CSP_STYLE_SRC", str, ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"]
  210. )
  211. CSP_STYLE_SRC_ELEM = env.list(
  212. "CSP_STYLE_SRC_ELEM",
  213. str,
  214. ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
  215. )
  216. CSP_FONT_SRC = env.list(
  217. "CSP_FONT_SRC", str, ["'self'", "https://fonts.gstatic.com", "data:"]
  218. )
  219. # Redoc requires blob
  220. CSP_WORKER_SRC = env.list("CSP_WORKER_SRC", str, ["'self'", "blob:"])
  221. # GlitchTip can record it's own errors
  222. CSP_CONNECT_SRC = env.list(
  223. "CSP_CONNECT_SRC",
  224. str,
  225. ["'self'", "https://*.glitchtip.com", "https://app.chatwoot.com"],
  226. )
  227. # Needed for Analytics and Stripe for SaaS use cases. Both are disabled by default.
  228. CSP_SCRIPT_SRC = env.list(
  229. "CSP_SCRIPT_SRC",
  230. str,
  231. ["'self'", "https://*.glitchtip.com", "https://js.stripe.com"],
  232. )
  233. CSP_IMG_SRC = env.list("CSP_IMG_SRC", str, ["'self'"])
  234. CSP_FRAME_SRC = env.list("CSP_FRAME_SRC", str, ["'self'", "https://js.stripe.com"])
  235. # Consider tracking CSP reports with GlitchTip itself
  236. CSP_REPORT_URI = env.tuple("CSP_REPORT_URI", str, None)
  237. CSP_REPORT_ONLY = env.bool("CSP_REPORT_ONLY", False)
  238. SECURE_HSTS_SECONDS = env.int("SECURE_HSTS_SECONDS", 0)
  239. SECURE_HSTS_PRELOAD = env.bool("SECURE_HSTS_PRELOAD", False)
  240. SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("SECURE_HSTS_INCLUDE_SUBDOMAINS", False)
  241. SESSION_COOKIE_SECURE = env.bool("SESSION_COOKIE_SECURE", False)
  242. SESSION_COOKIE_SAMESITE = env.str("SESSION_COOKIE_SAMESITE", "Lax")
  243. DEFAULT_FROM_EMAIL = env.str("DEFAULT_FROM_EMAIL", "webmaster@localhost")
  244. ANYMAIL = {
  245. "MAILGUN_API_KEY": env.str("MAILGUN_API_KEY", None),
  246. "MAILGUN_SENDER_DOMAIN": env.str("MAILGUN_SENDER_DOMAIN", None),
  247. "MAILGUN_API_URL": env.str("MAILGUN_API_URL", "https://api.mailgun.net/v3"),
  248. }
  249. ACCOUNT_EMAIL_SUBJECT_PREFIX = ""
  250. # Database
  251. # https://docs.djangoproject.com/en/dev/ref/settings/#databases
  252. DATABASES = {
  253. "default": env.db(default="postgres://postgres:postgres@postgres:5432/postgres")
  254. }
  255. # Support setting DATABASES in parts in order to get values from the postgresql helm chart
  256. DATABASE_HOST = env.str("DATABASE_HOST", None)
  257. DATABASE_PASSWORD = env.str("DATABASE_PASSWORD", None)
  258. if DATABASE_HOST and DATABASE_PASSWORD:
  259. DATABASES["default"] = {
  260. "ENGINE": "django.db.backends.postgresql",
  261. "NAME": env.str("DATABASE_NAME", "postgres"),
  262. "USER": env.str("DATABASE_USER", "postgres"),
  263. "PASSWORD": DATABASE_PASSWORD,
  264. "HOST": DATABASE_HOST,
  265. "PORT": env.str("DATABASE_PORT", "5432"),
  266. }
  267. DEFAULT_AUTO_FIELD = "django.db.models.AutoField"
  268. # We need to support both url and broken out host to support helm redis chart
  269. REDIS_HOST = env.str("REDIS_HOST", None)
  270. if REDIS_HOST:
  271. REDIS_PORT = env.str("REDIS_PORT", "6379")
  272. REDIS_DATABASE = env.str("REDIS_DATABASE", "0")
  273. REDIS_PASSWORD = env.str("REDIS_PASSWORD", None)
  274. if REDIS_PASSWORD:
  275. REDIS_URL = (
  276. f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  277. )
  278. else:
  279. REDIS_URL = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DATABASE}"
  280. else:
  281. REDIS_URL = env.str("REDIS_URL", "redis://redis:6379/0")
  282. CELERY_BROKER_URL = REDIS_URL
  283. CELERY_BROKER_TRANSPORT_OPTIONS = {
  284. "fanout_prefix": True,
  285. "fanout_patterns": True,
  286. }
  287. CELERY_RESULT_BACKEND = "django-db"
  288. CELERY_CACHE_BACKEND = "django-cache"
  289. CELERY_BEAT_SCHEDULE = {
  290. "send-alert-notifications": {
  291. "task": "alerts.tasks.process_event_alerts",
  292. "schedule": 60,
  293. },
  294. "cleanup-old-events": {
  295. "task": "issues.tasks.cleanup_old_events",
  296. "schedule": crontab(hour=6, minute=1),
  297. },
  298. "cleanup-old-transaction-events": {
  299. "task": "performance.tasks.cleanup_old_transaction_events",
  300. "schedule": crontab(hour=6, minute=10),
  301. },
  302. "cleanup-old-monitor-checks": {
  303. "task": "glitchtip.uptime.tasks.cleanup_old_monitor_checks",
  304. "schedule": crontab(hour=6, minute=20),
  305. },
  306. "uptime-dispatch-checks": {
  307. "task": "glitchtip.uptime.tasks.dispatch_checks",
  308. "schedule": timedelta(seconds=30),
  309. },
  310. }
  311. CACHES = {
  312. "default": {
  313. "BACKEND": "django.core.cache.backends.redis.RedisCache",
  314. "LOCATION": REDIS_URL,
  315. }
  316. }
  317. # Password validation
  318. # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
  319. AUTH_PASSWORD_VALIDATORS = [
  320. {
  321. "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
  322. },
  323. {
  324. "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
  325. },
  326. {
  327. "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
  328. },
  329. {
  330. "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
  331. },
  332. ]
  333. # Internationalization
  334. # https://docs.djangoproject.com/en/dev/topics/i18n/
  335. LANGUAGE_CODE = "en-us"
  336. TIME_ZONE = "UTC"
  337. USE_I18N = True
  338. USE_L10N = True
  339. USE_TZ = True
  340. SITE_ID = 1
  341. # Static files (CSS, JavaScript, Images)
  342. # https://docs.djangoproject.com/en/dev/howto/static-files/
  343. STATIC_URL = "/static/"
  344. if env("DEFAULT_FILE_STORAGE"):
  345. DEFAULT_FILE_STORAGE = env("DEFAULT_FILE_STORAGE")
  346. GS_BUCKET_NAME = env("GS_BUCKET_NAME")
  347. AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID")
  348. AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
  349. AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME")
  350. AWS_S3_ENDPOINT_URL = env("AWS_S3_ENDPOINT_URL")
  351. AWS_LOCATION = env("AWS_LOCATION")
  352. if AWS_S3_ENDPOINT_URL:
  353. MEDIA_URL = env.str(
  354. "MEDIA_URL", "https://%s/%s/" % (AWS_S3_ENDPOINT_URL, AWS_LOCATION)
  355. )
  356. DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
  357. else:
  358. MEDIA_URL = "media/"
  359. MEDIA_ROOT = env.str("MEDIA_ROOT", "")
  360. STATICFILES_DIRS = [
  361. "assets",
  362. "dist",
  363. ]
  364. STATIC_ROOT = path("static/")
  365. STATICFILES_STORAGE = env("STATICFILES_STORAGE")
  366. EMAIL_BACKEND = env.str(
  367. "EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
  368. )
  369. if os.getenv("EMAIL_URL"):
  370. EMAIL_CONFIG = env.email_url("EMAIL_URL")
  371. vars().update(EMAIL_CONFIG)
  372. AUTH_USER_MODEL = "users.User"
  373. ACCOUNT_AUTHENTICATION_METHOD = "email"
  374. ACCOUNT_EMAIL_REQUIRED = True
  375. ACCOUNT_USERNAME_REQUIRED = False
  376. ACCOUNT_USER_MODEL_USERNAME_FIELD = None
  377. ACCOUNT_ADAPTER = "glitchtip.social.MFAAccountAdapter"
  378. INVITATION_BACKEND = "organizations_ext.invitation_backend.InvitationBackend"
  379. SOCIALACCOUNT_PROVIDERS = {}
  380. GITLAB_URL = env.url("SOCIALACCOUNT_PROVIDERS_gitlab_GITLAB_URL", None)
  381. if GITLAB_URL:
  382. SOCIALACCOUNT_PROVIDERS["gitlab"] = {"GITLAB_URL": GITLAB_URL.geturl()}
  383. GITEA_URL = env.url("SOCIALACCOUNT_PROVIDERS_gitea_GITEA_URL", None)
  384. if GITEA_URL:
  385. SOCIALACCOUNT_PROVIDERS["gitea"] = {"GITEA_URL": GITEA_URL.geturl()}
  386. NEXTCLOUD_URL = env.url("SOCIALACCOUNT_PROVIDERS_nextcloud_SERVER", None)
  387. if NEXTCLOUD_URL:
  388. SOCIALACCOUNT_PROVIDERS["nextcloud"] = {"SERVER": NEXTCLOUD_URL.geturl()}
  389. OLD_PASSWORD_FIELD_ENABLED = True
  390. LOGOUT_ON_PASSWORD_CHANGE = False
  391. REST_AUTH_SERIALIZERS = {
  392. "USER_DETAILS_SERIALIZER": "users.serializers.UserSerializer",
  393. "TOKEN_SERIALIZER": "users.serializers.NoopTokenSerializer",
  394. "PASSWORD_RESET_SERIALIZER": "users.serializers.PasswordSetResetSerializer",
  395. }
  396. REST_AUTH_REGISTER_SERIALIZERS = {
  397. "REGISTER_SERIALIZER": "users.serializers.RegisterSerializer",
  398. }
  399. REST_AUTH_TOKEN_MODEL = None
  400. REST_AUTH_TOKEN_CREATOR = "users.utils.noop_token_creator"
  401. # By default (False) only the first user, superuser, or organization owners may register
  402. # and create an organization. Other users must be invited. Intended for private instances
  403. ENABLE_OPEN_USER_REGISTRATION = env.bool("ENABLE_OPEN_USER_REGISTRATION", False)
  404. AUTHENTICATION_BACKENDS = (
  405. # Needed to login by username in Django admin, regardless of `allauth`
  406. "django.contrib.auth.backends.ModelBackend",
  407. # `allauth` specific authentication methods, such as login by e-mail
  408. "allauth.account.auth_backends.AuthenticationBackend",
  409. )
  410. DEFAULT_RENDERER_CLASSES = ("rest_framework.renderers.JSONRenderer",)
  411. if DEBUG:
  412. DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
  413. "rest_framework.renderers.BrowsableAPIRenderer",
  414. )
  415. REST_FRAMEWORK = {
  416. "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
  417. "DEFAULT_PAGINATION_CLASS": "glitchtip.pagination.LinkHeaderPagination",
  418. "PAGE_SIZE": 50,
  419. "ORDERING_PARAM": "sort",
  420. "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
  421. "DEFAULT_RENDERER_CLASSES": DEFAULT_RENDERER_CLASSES,
  422. "DEFAULT_AUTHENTICATION_CLASSES": [
  423. "rest_framework.authentication.SessionAuthentication",
  424. "glitchtip.authentication.BearerTokenAuthentication",
  425. ],
  426. "DEFAULT_THROTTLE_RATES": {"anon": "100/minute"},
  427. }
  428. DRF_YASG_EXCLUDE_VIEWS = [
  429. "users.views.SocialAccountDisconnectView",
  430. ]
  431. SWAGGER_SETTINGS = {
  432. "DEFAULT_AUTO_SCHEMA_CLASS": "glitchtip.yasg.SquadSwaggerAutoSchema",
  433. }
  434. LOGGING_HANDLER_CLASS = env.str("DJANGO_LOGGING_HANDLER_CLASS", "logging.StreamHandler")
  435. LOGGING = {
  436. "version": 1,
  437. "disable_existing_loggers": False,
  438. "handlers": {
  439. "null": {
  440. "class": "logging.NullHandler",
  441. },
  442. "console": {
  443. "class": LOGGING_HANDLER_CLASS,
  444. },
  445. },
  446. "loggers": {
  447. "django.security.DisallowedHost": {
  448. "handlers": ["null"],
  449. "propagate": False,
  450. },
  451. },
  452. "root": {"handlers": ["console"]},
  453. }
  454. if LOGGING_HANDLER_CLASS is not logging.StreamHandler:
  455. from celery.signals import after_setup_logger, after_setup_task_logger
  456. @after_setup_logger.connect
  457. @after_setup_task_logger.connect
  458. def setup_celery_logging(logger, **kwargs):
  459. from django.utils.module_loading import import_string
  460. handler = import_string(LOGGING_HANDLER_CLASS)
  461. for h in logger.handlers:
  462. logger.removeHandler(h)
  463. logger.addHandler(handler())
  464. def organization_request_callback(request):
  465. """Gets an organization instance from the id passed through ``request``"""
  466. user = request.user
  467. if user:
  468. return user.organizations_ext_organization.filter(
  469. owner__organization_user__user=user
  470. ).first()
  471. # Set to track activity with Plausible
  472. PLAUSIBLE_URL = env.str("PLAUSIBLE_URL", default=None)
  473. PLAUSIBLE_DOMAIN = env.str("PLAUSIBLE_DOMAIN", default=None)
  474. # Set to chatwoot website token to enable live help widget. Assumes app.chatwoot.com.
  475. CHATWOOT_WEBSITE_TOKEN = env.str("CHATWOOT_WEBSITE_TOKEN", None)
  476. # Is running unit test
  477. TESTING = len(sys.argv) > 1 and sys.argv[1] == "test"
  478. # See https://liberapay.com/GlitchTip/donate - suggested self-host donation is $5/month/user.
  479. # Support plans available. Email info@burkesoftware.com for more info.
  480. I_PAID_FOR_GLITCHTIP = env.bool("I_PAID_FOR_GLITCHTIP", False)
  481. # Max events per month for free tier
  482. BILLING_FREE_TIER_EVENTS = env.int("BILLING_FREE_TIER_EVENTS", 1000)
  483. DJSTRIPE_SUBSCRIBER_MODEL = "organizations_ext.Organization"
  484. DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK = organization_request_callback
  485. DJSTRIPE_USE_NATIVE_JSONFIELD = True
  486. DJSTRIPE_FOREIGN_KEY_TO_FIELD = "djstripe_id"
  487. STRIPE_AUTOMATIC_TAX = env.bool("STRIPE_AUTOMATIC_TAX", False)
  488. BILLING_ENABLED = False
  489. STRIPE_LIVE_MODE = env.bool("STRIPE_LIVE_MODE", False)
  490. if env.str("STRIPE_TEST_PUBLIC_KEY", None) or env.str("STRIPE_LIVE_PUBLIC_KEY", None):
  491. BILLING_ENABLED = True
  492. I_PAID_FOR_GLITCHTIP = True
  493. INSTALLED_APPS.append("djstripe")
  494. INSTALLED_APPS.append("djstripe_ext")
  495. STRIPE_TEST_PUBLIC_KEY = env.str("STRIPE_TEST_PUBLIC_KEY", None)
  496. STRIPE_TEST_SECRET_KEY = env.str("STRIPE_TEST_SECRET_KEY", None)
  497. STRIPE_LIVE_PUBLIC_KEY = env.str("STRIPE_LIVE_PUBLIC_KEY", None)
  498. STRIPE_LIVE_SECRET_KEY = env.str("STRIPE_LIVE_SECRET_KEY", None)
  499. DJSTRIPE_WEBHOOK_SECRET = env.str("DJSTRIPE_WEBHOOK_SECRET", None)
  500. CELERY_BEAT_SCHEDULE["set-organization-throttle"] = {
  501. "task": "organizations_ext.tasks.set_organization_throttle",
  502. "schedule": crontab(hour=7, minute=1),
  503. }
  504. CELERY_BEAT_SCHEDULE["warn-organization-throttle"] = {
  505. "task": "djstripe_ext.tasks.warn_organization_throttle",
  506. "schedule": crontab(minute=30),
  507. }
  508. elif TESTING:
  509. # Must run tests with djstripe enabled
  510. BILLING_ENABLED = True
  511. INSTALLED_APPS.append("djstripe")
  512. INSTALLED_APPS.append("djstripe_ext")
  513. STRIPE_TEST_PUBLIC_KEY = "fake"
  514. STRIPE_TEST_SECRET_KEY = "sk_test_fake" # nosec
  515. DJSTRIPE_WEBHOOK_SECRET = "whsec_fake" # nosec
  516. logging.disable(logging.WARNING)
  517. CELERY_TASK_ALWAYS_EAGER = env.bool("CELERY_TASK_ALWAYS_EAGER", False)
  518. if TESTING:
  519. CELERY_TASK_ALWAYS_EAGER = True
  520. STATICFILES_STORAGE = None
  521. # https://github.com/evansd/whitenoise/issues/215
  522. warnings.filterwarnings(
  523. "ignore", message="No directory at", module="whitenoise.base"
  524. )
  525. if CELERY_TASK_ALWAYS_EAGER:
  526. CACHES = {
  527. "default": {
  528. "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
  529. }
  530. }
  531. MFA_SERVER_NAME = "GlitchTip"
  532. FIDO_SERVER_ID = GLITCHTIP_URL.hostname
  533. # Workaround for error encountered at build time (source: https://github.com/axnsan12/drf-yasg/issues/761#issuecomment-1014530805)
  534. class NoSourceMapsStorage(CompressedManifestStaticFilesStorage):
  535. patterns = (
  536. (
  537. "*.css",
  538. (
  539. "(?P<matched>url\\(['\"]{0,1}\\s*(?P<url>.*?)[\"']{0,1}\\))",
  540. (
  541. "(?P<matched>@import\\s*[\"']\\s*(?P<url>.*?)[\"'])",
  542. '@import url("%(url)s")',
  543. ),
  544. ),
  545. ),
  546. )