settings.py 22 KB

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