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.

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