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.

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