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.

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