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.

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