You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

377 lines
13 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
  1. """
  2. Django settings for app project.
  3. For more information on this file, see
  4. https://docs.djangoproject.com/en/2.0/topics/settings/
  5. For the full list of settings and their values, see
  6. https://docs.djangoproject.com/en/2.0/ref/settings/
  7. Any setting that is configured via an environment variable may
  8. also be set in a `.env` file in the project base directory.
  9. """
  10. import importlib.util
  11. import sys
  12. from os import path
  13. import dj_database_url
  14. from environs import Env, EnvError
  15. from furl import furl
  16. # Build paths inside the project like this: path.join(BASE_DIR, ...)
  17. BASE_DIR = path.dirname(path.dirname(path.abspath(__file__)))
  18. env = Env()
  19. env.read_env(path.join(BASE_DIR, '.env'), recurse=False)
  20. # Quick-start development settings - unsuitable for production
  21. # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
  22. # SECURITY WARNING: keep the secret key used in production secret!
  23. SECRET_KEY = env('SECRET_KEY',
  24. 'v8sk33sy82!uw3ty=!jjv5vp7=s2phrzw(m(hrn^f7e_#1h2al')
  25. # SECURITY WARNING: don't run with debug turned on in production!
  26. DEBUG = env.bool('DEBUG', True)
  27. # True if you want to allow users to be able to create an account
  28. ALLOW_SIGNUP = env.bool('ALLOW_SIGNUP', True)
  29. # ALLOWED_HOSTS = []
  30. # Application definition
  31. INSTALLED_APPS = [
  32. 'whitenoise.runserver_nostatic',
  33. 'django.contrib.admin',
  34. 'django.contrib.auth',
  35. 'django.contrib.contenttypes',
  36. 'django.contrib.sessions',
  37. 'django.contrib.messages',
  38. 'django.contrib.staticfiles',
  39. 'api.apps.ApiConfig',
  40. 'roles.apps.RolesConfig',
  41. 'members.apps.MembersConfig',
  42. 'metrics.apps.MetricsConfig',
  43. 'users.apps.UsersConfig',
  44. 'data_import.apps.DataImportConfig',
  45. 'data_export.apps.DataExportConfig',
  46. 'auto_labeling.apps.AutoLabelingConfig',
  47. 'labels.apps.LabelsConfig',
  48. 'label_types.apps.LabelTypesConfig',
  49. 'examples.apps.ExamplesConfig',
  50. 'rest_framework',
  51. 'rest_framework.authtoken',
  52. 'django_filters',
  53. 'social_django',
  54. 'polymorphic',
  55. 'corsheaders',
  56. 'drf_yasg',
  57. 'dj_rest_auth',
  58. 'django_celery_results',
  59. 'django_drf_filepond',
  60. 'health_check',
  61. 'health_check.cache',
  62. 'health_check.storage',
  63. 'health_check.contrib.migrations',
  64. 'health_check.contrib.celery',
  65. ]
  66. CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER = env('CLOUD_BROWSER_LIBCLOUD_PROVIDER', None)
  67. CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT = env('CLOUD_BROWSER_LIBCLOUD_ACCOUNT', None)
  68. CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY = env('CLOUD_BROWSER_LIBCLOUD_KEY', None)
  69. if CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER:
  70. CLOUD_BROWSER_DATASTORE = 'ApacheLibcloud'
  71. CLOUD_BROWSER_OBJECT_REDIRECT_URL = '/v1/cloud-upload'
  72. INSTALLED_APPS.append('cloud_browser')
  73. MIDDLEWARE = [
  74. 'django.middleware.security.SecurityMiddleware',
  75. 'whitenoise.middleware.WhiteNoiseMiddleware',
  76. 'django.contrib.sessions.middleware.SessionMiddleware',
  77. 'django.middleware.common.CommonMiddleware',
  78. 'django.middleware.csrf.CsrfViewMiddleware',
  79. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  80. 'django.contrib.messages.middleware.MessageMiddleware',
  81. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  82. 'social_django.middleware.SocialAuthExceptionMiddleware',
  83. # 'applicationinsights.django.ApplicationInsightsMiddleware',
  84. 'corsheaders.middleware.CorsMiddleware',
  85. ]
  86. if DEBUG:
  87. MIDDLEWARE.append('api.middleware.RangesMiddleware')
  88. ROOT_URLCONF = 'app.urls'
  89. TEMPLATES = [
  90. {
  91. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  92. 'DIRS': [path.join(BASE_DIR, 'client/dist')],
  93. 'APP_DIRS': True,
  94. 'OPTIONS': {
  95. 'context_processors': [
  96. 'django.template.context_processors.debug',
  97. 'django.template.context_processors.request',
  98. 'django.contrib.auth.context_processors.auth',
  99. 'django.contrib.messages.context_processors.messages',
  100. 'social_django.context_processors.backends',
  101. 'social_django.context_processors.login_redirect',
  102. ],
  103. },
  104. },
  105. ]
  106. # Static files (CSS, JavaScript, Images)
  107. # https://docs.djangoproject.com/en/2.0/howto/static-files/
  108. STATIC_URL = '/static/'
  109. STATIC_ROOT = path.join(BASE_DIR, 'staticfiles')
  110. STATICFILES_DIRS = [
  111. path.join(BASE_DIR, 'client/dist/static'),
  112. ]
  113. STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
  114. WSGI_APPLICATION = 'app.wsgi.application'
  115. AUTHENTICATION_BACKENDS = [
  116. 'social_core.backends.github.GithubOAuth2',
  117. 'social_core.backends.azuread_tenant.AzureADTenantOAuth2',
  118. 'social_core.backends.okta.OktaOAuth2',
  119. 'social_core.backends.okta_openidconnect.OktaOpenIdConnect',
  120. 'django.contrib.auth.backends.ModelBackend',
  121. ]
  122. HEADER_AUTH_USER_NAME = env('HEADER_AUTH_USER_NAME', '')
  123. HEADER_AUTH_USER_GROUPS = env('HEADER_AUTH_USER_GROUPS', '')
  124. HEADER_AUTH_ADMIN_GROUP_NAME = env('HEADER_AUTH_ADMIN_GROUP_NAME', '')
  125. HEADER_AUTH_GROUPS_SEPERATOR = env('HEADER_AUTH_GROUPS_SEPERATOR', default=',')
  126. if HEADER_AUTH_USER_NAME and HEADER_AUTH_USER_GROUPS and HEADER_AUTH_ADMIN_GROUP_NAME:
  127. MIDDLEWARE.append('api.middleware.HeaderAuthMiddleware')
  128. AUTHENTICATION_BACKENDS.append('django.contrib.auth.backends.RemoteUserBackend')
  129. SOCIAL_AUTH_GITHUB_KEY = env('OAUTH_GITHUB_KEY', None)
  130. SOCIAL_AUTH_GITHUB_SECRET = env('OAUTH_GITHUB_SECRET', None)
  131. GITHUB_ADMIN_ORG_NAME = env('GITHUB_ADMIN_ORG_NAME', None)
  132. GITHUB_ADMIN_TEAM_NAME = env('GITHUB_ADMIN_TEAM_NAME', None)
  133. if GITHUB_ADMIN_ORG_NAME and GITHUB_ADMIN_TEAM_NAME:
  134. SOCIAL_AUTH_GITHUB_SCOPE = ['read:org']
  135. SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = env('OAUTH_AAD_KEY', None)
  136. SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = env('OAUTH_AAD_SECRET', None)
  137. SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = env('OAUTH_AAD_TENANT', None)
  138. AZUREAD_ADMIN_GROUP_ID = env('AZUREAD_ADMIN_GROUP_ID', None)
  139. if AZUREAD_ADMIN_GROUP_ID:
  140. SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_RESOURCE = 'https://graph.microsoft.com/'
  141. SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SCOPE = ['Directory.Read.All']
  142. SOCIAL_AUTH_OKTA_OAUTH2_KEY = env('OAUTH_OKTA_OAUTH2_KEY', None)
  143. SOCIAL_AUTH_OKTA_OAUTH2_SECRET = env('OAUTH_OKTA_OAUTH2_SECRET', None)
  144. SOCIAL_AUTH_OKTA_OAUTH2_API_URL = env('OAUTH_OKTA_OAUTH2_API_URL', None)
  145. OKTA_OAUTH2_ADMIN_GROUP_NAME = env('OKTA_OAUTH2_ADMIN_GROUP_NAME', None)
  146. if SOCIAL_AUTH_OKTA_OAUTH2_API_URL:
  147. SOCIAL_AUTH_OKTA_OAUTH2_SCOPE = ["groups"]
  148. SOCIAL_AUTH_OKTA_OPENIDCONNECT_KEY = env('OAUTH_OKTA_OPENIDCONNECT_KEY', None)
  149. SOCIAL_AUTH_OKTA_OPENIDCONNECT_SECRET = env('OAUTH_OKTA_OPENIDCONNECT_SECRET', None)
  150. SOCIAL_AUTH_OKTA_OPENIDCONNECT_API_URL = env('OAUTH_OKTA_OPENIDCONNECT_API_URL', None)
  151. OKTA_OPENIDCONNECT_ADMIN_GROUP_NAME = env('OKTA_OPENIDCONNECT_ADMIN_GROUP_NAME', None)
  152. if SOCIAL_AUTH_OKTA_OPENIDCONNECT_API_URL:
  153. SOCIAL_AUTH_OKTA_OPENIDCONNECT_SCOPE = ["groups"]
  154. SOCIAL_AUTH_PIPELINE = [
  155. 'social_core.pipeline.social_auth.social_details',
  156. 'social_core.pipeline.social_auth.social_uid',
  157. 'social_core.pipeline.social_auth.auth_allowed',
  158. 'social_core.pipeline.social_auth.social_user',
  159. 'social_core.pipeline.user.get_username',
  160. 'social_core.pipeline.user.create_user',
  161. 'social_core.pipeline.social_auth.associate_user',
  162. 'social_core.pipeline.social_auth.load_extra_data',
  163. 'social_core.pipeline.user.user_details',
  164. ]
  165. ROLE_PROJECT_ADMIN = env('ROLE_PROJECT_ADMIN', 'project_admin')
  166. ROLE_ANNOTATOR = env('ROLE_ANNOTATOR', 'annotator')
  167. ROLE_ANNOTATION_APPROVER = env('ROLE_ANNOTATION_APPROVER', 'annotation_approver')
  168. # Database
  169. # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
  170. DATABASES = {
  171. 'default': {
  172. 'ENGINE': 'django.db.backends.sqlite3',
  173. 'NAME': path.join(BASE_DIR, 'db.sqlite3'),
  174. }
  175. }
  176. # Password validation
  177. # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
  178. AUTH_PASSWORD_VALIDATORS = [
  179. {
  180. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  181. },
  182. {
  183. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  184. },
  185. {
  186. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  187. },
  188. {
  189. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  190. },
  191. ]
  192. REST_FRAMEWORK = {
  193. # Use Django's standard `django.contrib.auth` permissions,
  194. # or allow read-only access for unauthenticated users.
  195. 'DEFAULT_PERMISSION_CLASSES': [
  196. 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
  197. 'rest_framework.permissions.IsAuthenticated',
  198. ],
  199. 'DEFAULT_AUTHENTICATION_CLASSES': (
  200. 'rest_framework.authentication.SessionAuthentication',
  201. 'rest_framework.authentication.TokenAuthentication',
  202. ),
  203. 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
  204. 'PAGE_SIZE': env.int('DOCCANO_PAGE_SIZE', default=5),
  205. 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
  206. 'SEARCH_PARAM': 'q',
  207. 'DEFAULT_RENDERER_CLASSES': (
  208. 'rest_framework.renderers.JSONRenderer',
  209. 'rest_framework.renderers.BrowsableAPIRenderer',
  210. 'rest_framework_xml.renderers.XMLRenderer'
  211. )
  212. }
  213. # Internationalization
  214. # https://docs.djangoproject.com/en/2.0/topics/i18n/
  215. LANGUAGE_CODE = 'en-us'
  216. TIME_ZONE = 'UTC'
  217. USE_I18N = True
  218. USE_L10N = True
  219. USE_TZ = True
  220. TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
  221. TEST_OUTPUT_DIR = path.join(BASE_DIR, 'junitxml')
  222. LOGIN_URL = '/login/'
  223. LOGIN_REDIRECT_URL = '/projects/'
  224. LOGOUT_REDIRECT_URL = '/'
  225. # dynamic import to avoid installing psycopg2 on pip installation.
  226. name = 'django_heroku'
  227. spec = importlib.util.find_spec(name)
  228. if spec is not None:
  229. module = importlib.util.module_from_spec(spec)
  230. sys.modules[name] = module
  231. spec.loader.exec_module(module)
  232. module.settings(locals(), test_runner=False)
  233. # Change 'default' database configuration with $DATABASE_URL.
  234. DATABASES['default'].update(dj_database_url.config(
  235. env='DATABASE_URL',
  236. conn_max_age=env.int('DATABASE_CONN_MAX_AGE', 500),
  237. ssl_require='sslmode' not in furl(env('DATABASE_URL', '')).args,
  238. ))
  239. # work-around for dj-database-url: explicitly disable ssl for sqlite
  240. if DATABASES['default'].get('ENGINE') == 'django.db.backends.sqlite3':
  241. DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)
  242. # work-around for dj-database-url: patch ssl for mysql
  243. if DATABASES['default'].get('ENGINE') == 'django.db.backends.mysql':
  244. DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)
  245. if env('MYSQL_SSL_CA', None):
  246. DATABASES['default'].setdefault('OPTIONS', {})\
  247. .setdefault('ssl', {}).setdefault('ca', env('MYSQL_SSL_CA', None))
  248. # default to a sensible modern driver for Azure SQL
  249. if DATABASES['default'].get('ENGINE') == 'sql_server.pyodbc':
  250. DATABASES['default'].setdefault('OPTIONS', {})\
  251. .setdefault('driver', 'ODBC Driver 17 for SQL Server')
  252. # Honor the 'X-Forwarded-Proto' header for request.is_secure()
  253. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
  254. SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', False)
  255. CSRF_COOKIE_SECURE = env.bool('CSRF_COOKIE_SECURE', False)
  256. CSRF_TRUSTED_ORIGINS = env.list('CSRF_TRUSTED_ORIGINS', [])
  257. # Allow all host headers
  258. ALLOWED_HOSTS = ['*']
  259. # Size of the batch for creating documents
  260. # on the import phase
  261. IMPORT_BATCH_SIZE = env.int('IMPORT_BATCH_SIZE', 1000)
  262. GOOGLE_TRACKING_ID = env('GOOGLE_TRACKING_ID', 'UA-125643874-2').strip()
  263. AZURE_APPINSIGHTS_IKEY = env('AZURE_APPINSIGHTS_IKEY', None)
  264. APPLICATION_INSIGHTS = {
  265. 'ikey': AZURE_APPINSIGHTS_IKEY if AZURE_APPINSIGHTS_IKEY else None,
  266. 'endpoint': env('AZURE_APPINSIGHTS_ENDPOINT', None),
  267. }
  268. # necessary for email verification of new accounts
  269. EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', False)
  270. EMAIL_HOST = env('EMAIL_HOST', None)
  271. EMAIL_HOST_USER = env('EMAIL_HOST_USER', None)
  272. EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', None)
  273. EMAIL_PORT = env.int('EMAIL_PORT', 587)
  274. DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', 'webmaster@localhost')
  275. if not EMAIL_HOST:
  276. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
  277. if DEBUG:
  278. CORS_ORIGIN_WHITELIST = (
  279. 'http://127.0.0.1:3000',
  280. 'http://0.0.0.0:3000',
  281. 'http://localhost:3000'
  282. )
  283. MEDIA_ROOT = path.join(BASE_DIR, 'media')
  284. MEDIA_URL = '/media/'
  285. # Filepond settings.
  286. DJANGO_DRF_FILEPOND_UPLOAD_TMP = path.join(BASE_DIR, 'filepond-temp-uploads')
  287. DJANGO_DRF_FILEPOND_FILE_STORE_PATH = MEDIA_ROOT
  288. # Celery settings
  289. DJANGO_CELERY_RESULTS_TASK_ID_MAX_LENGTH = 191
  290. CELERY_RESULT_BACKEND = 'django-db'
  291. try:
  292. CELERY_BROKER_URL = env('CELERY_BROKER_URL')
  293. except EnvError:
  294. try:
  295. # quickfix for Heroku.
  296. # See https://github.com/doccano/doccano/issues/1327.
  297. uri = env('DATABASE_URL')
  298. if uri.startswith('postgres://'):
  299. uri = uri.replace('postgres://', 'postgresql://', 1)
  300. CELERY_BROKER_URL = 'sqla+{}'.format(uri)
  301. except EnvError:
  302. CELERY_BROKER_URL = 'sqla+sqlite:///{}'.format(DATABASES['default']['NAME'])
  303. CELERY_ACCEPT_CONTENT = ['application/json']
  304. CELERY_TASK_SERIALIZER = 'json'
  305. CELERY_RESULT_SERIALIZER = 'json'
  306. DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'