-
-
Notifications
You must be signed in to change notification settings - Fork 185
/
Copy pathbase.py
1835 lines (1656 loc) · 66.4 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
import string
import subprocess
import warnings
from datetime import datetime, timedelta
from mimetypes import add_type
from urllib.parse import quote_plus
import django.conf.locale
import environ
from celery.schedules import crontab
from django.conf import global_settings
from django.urls import reverse_lazy
from django.utils.translation import get_language_info
from django.utils.translation import gettext_lazy as t
from pymongo import MongoClient
from kobo.apps.stripe.constants import FREE_TIER_EMPTY_DISPLAY, FREE_TIER_NO_THRESHOLDS
from kpi.constants import PERM_DELETE_ASSET, PERM_MANAGE_ASSET
from kpi.utils.json import LazyJSONSerializable
from ..static_lists import EXTRA_LANG_INFO, SECTOR_CHOICE_DEFAULTS
env = environ.Env()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
settings_dirname = os.path.dirname(os.path.abspath(__file__))
parent_dirname = os.path.dirname(settings_dirname)
BASE_DIR = os.path.abspath(os.path.dirname(parent_dirname))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str('DJANGO_SECRET_KEY', '@25)**hc^rjaiagb4#&q*84hr*uscsxwr-cv#0joiwj$))obyk')
# Optionally treat proxied connections as secure.
# See: https://docs.djangoproject.com/en/1.8/ref/settings/#secure-proxy-ssl-header.
# Example environment: `export SECURE_PROXY_SSL_HEADER='HTTP_X_FORWARDED_PROTO, https'`.
# SECURITY WARNING: If enabled, outer web server must filter out the `X-Forwarded-Proto` header.
SECURE_PROXY_SSL_HEADER = env.tuple('SECURE_PROXY_SSL_HEADER', str, None)
public_request_scheme = env.str('PUBLIC_REQUEST_SCHEME', 'https').lower()
if public_request_scheme == 'https' or SECURE_PROXY_SSL_HEADER:
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool('SECURE_HSTS_INCLUDE_SUBDOMAINS', False)
SECURE_HSTS_PRELOAD = env.bool('SECURE_HSTS_PRELOAD', False)
SECURE_HSTS_SECONDS = env.int('SECURE_HSTS_SECONDS', 0)
# Make Django use NginX $host. Useful when running with ./manage.py runserver_plus
# It avoids adding the debugger webserver port (i.e. `:8000`) at the end of urls.
USE_X_FORWARDED_HOST = env.bool('USE_X_FORWARDED_HOST', False)
# Domain must not exclude KoBoCAT when sharing sessions
SESSION_COOKIE_DOMAIN = env.str('SESSION_COOKIE_DOMAIN', None)
if SESSION_COOKIE_DOMAIN:
SESSION_COOKIE_NAME = env.str('SESSION_COOKIE_NAME', 'kobonaut')
# The trusted CSRF origins must encompass Enketo's subdomain. See
# https://docs.djangoproject.com/en/2.2/ref/settings/#std:setting-CSRF_TRUSTED_ORIGINS
trusted_domains = [
f'{public_request_scheme}://*{SESSION_COOKIE_DOMAIN}',
]
CSRF_TRUSTED_ORIGINS = trusted_domains
ENKETO_CSRF_COOKIE_NAME = env.str('ENKETO_CSRF_COOKIE_NAME', '__csrf')
# Limit sessions to 1 week (the default is 2 weeks)
SESSION_COOKIE_AGE = env.int('DJANGO_SESSION_COOKIE_AGE', 604800)
# Set language cookie age to same value as session cookie
LANGUAGE_COOKIE_AGE = SESSION_COOKIE_AGE
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DJANGO_DEBUG', False)
ALLOWED_HOSTS = env.str('DJANGO_ALLOWED_HOSTS', '*').split(' ')
LOGIN_REDIRECT_URL = 'kpi-root'
LOGOUT_REDIRECT_URL = 'kobo_login' # Use URL pattern instead of hard-coded value
# Application definition
# The order of INSTALLED_APPS is important for template resolution. When two
# apps both define templates for the same view, the first app listed receives
# precedence
INSTALLED_APPS = (
# Always put `contenttypes` before `auth`; see
# https://code.djangoproject.com/ticket/10827
'django.contrib.contenttypes',
'django.contrib.admin',
'kobo.apps.kobo_auth.KoboAuthAppConfig',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_prometheus',
'reversion',
'private_storage',
'kobo.apps.KpiConfig',
'kobo.apps.accounts',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.microsoft',
'allauth.socialaccount.providers.openid_connect',
'allauth.usersessions',
'hub.HubAppConfig',
'import_export',
'loginas',
'webpack_loader',
'django_extensions',
'django_filters',
'taggit',
'rest_framework',
'rest_framework.authtoken',
'oauth2_provider',
'django_digest',
'kobo.apps.organizations',
'kobo.apps.superuser_stats.SuperuserStatsAppConfig',
'kobo.apps.service_health',
'kobo.apps.subsequences',
'constance',
'kobo.apps.hook',
'django_celery_beat',
'corsheaders',
'kobo.apps.external_integrations.ExternalIntegrationsAppConfig',
'markdownx',
'kobo.apps.help',
'trench',
'kobo.apps.accounts.mfa.apps.MfaAppConfig',
'kobo.apps.languages.LanguageAppConfig',
'kobo.apps.project_views.ProjectViewAppConfig',
'kobo.apps.audit_log.AuditLogAppConfig',
'kobo.apps.trackers.TrackersConfig',
'kobo.apps.trash_bin.TrashBinAppConfig',
'kobo.apps.markdownx_uploader.MarkdownxUploaderAppConfig',
'kobo.apps.form_disclaimer.FormDisclaimerAppConfig',
'kobo.apps.openrosa.apps.logger.app.LoggerAppConfig',
'kobo.apps.openrosa.apps.viewer.app.ViewerConfig',
'kobo.apps.openrosa.apps.main.app.MainConfig',
'kobo.apps.openrosa.apps.api',
'guardian',
'kobo.apps.openrosa.libs',
'kobo.apps.project_ownership.app.ProjectOwnershipAppConfig',
'kobo.apps.long_running_migrations.app.LongRunningMigrationAppConfig',
)
MIDDLEWARE = [
'kobo.apps.service_health.middleware.HealthCheckMiddleware',
'kobo.apps.openrosa.koboform.redirect_middleware.ConditionalRedirects',
'kobo.apps.openrosa.apps.main.middleware.RevisionMiddleware',
'django_dont_vary_on.middleware.RemoveUnneededVaryHeadersMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'hub.middleware.LocaleMiddleware',
'allauth.account.middleware.AccountMiddleware',
'allauth.usersessions.middleware.UserSessionsMiddleware',
'django.middleware.common.CommonMiddleware',
'kobo.apps.audit_log.middleware.create_project_history_log_middleware',
# Still needed really?
'kobo.apps.openrosa.libs.utils.middleware.LocaleMiddlewareWithTweaks',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'kobo.apps.openrosa.libs.utils.middleware.RestrictedAccessMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'kobo.apps.openrosa.libs.utils.middleware.HTTPResponseNotAllowedMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'hub.middleware.UsernameInResponseHeaderMiddleware',
'django_userforeignkey.middleware.UserForeignKeyMiddleware',
'django_request_cache.middleware.RequestCacheMiddleware',
]
if os.environ.get('DEFAULT_FROM_EMAIL'):
DEFAULT_FROM_EMAIL = env.str('DEFAULT_FROM_EMAIL')
SERVER_EMAIL = DEFAULT_FROM_EMAIL
# Configuration options that superusers can modify in the Django admin
# interface. Please note that it's not as simple as moving a setting into the
# `CONSTANCE_CONFIG` dictionary: each place where the setting's value is needed
# must use `constance.config.THE_SETTING` instead of
# `django.conf.settings.THE_SETTING`
CONSTANCE_CONFIG = {
'REGISTRATION_OPEN': (
True,
'Allow new users to register accounts for themselves',
),
'REGISTRATION_ALLOWED_EMAIL_DOMAINS': (
'',
'Email domains allowed to register new accounts, one per line, '
'or blank to allow all email domains'
),
'REGISTRATION_DOMAIN_NOT_ALLOWED_ERROR_MESSAGE': (
'This email domain is not allowed to create an account',
'Error message for emails not listed in REGISTRATION_ALLOWED_EMAIL_DOMAINS '
'if field is not blank'
),
'TERMS_OF_SERVICE_URL': ('', 'URL for terms of service document'),
'PRIVACY_POLICY_URL': ('', 'URL for privacy policy'),
'SOURCE_CODE_URL': (
'https://github.com/kobotoolbox/',
'URL of source code repository. When empty, a link will not be shown '
'in the user interface',
),
'SUPPORT_EMAIL': (
env.str('KOBO_SUPPORT_EMAIL', env.str('DEFAULT_FROM_EMAIL', 'help@kobotoolbox.org')),
'Email address for users to contact, e.g. when they encounter '
'unhandled errors in the application',
),
'SUPPORT_URL': (
env.str('KOBO_SUPPORT_URL', 'https://support.kobotoolbox.org/'),
'URL for "KoboToolbox Help Center"',
),
'COMMUNITY_URL': (
env.str(
'KOBO_COMMUNITY_URL', 'https://community.kobotoolbox.org/'
),
'URL for "KoboToolbox Community Forum"',
),
'SYNCHRONOUS_EXPORT_CACHE_MAX_AGE': (
300,
'A synchronous export request will return the last export generated '
'with the same settings unless it is older than this value (seconds)'
),
'ALLOW_UNSECURED_HOOK_ENDPOINTS': (
True,
'Allow the use of unsecured endpoints for hooks. '
'(e.g http://hook.example.com)',
),
'HOOK_MAX_RETRIES': (
3,
'Number of times the system will retry to send data to remote server '
'before giving up',
),
'SSRF_ALLOWED_IP_ADDRESS': (
'',
'Whitelisted IP addresses to bypass SSRF protection\nOne per line',
),
'SSRF_DENIED_IP_ADDRESS': (
'',
'Blacklisted IP addresses to bypass SSRF protection\nOne per line',
),
'EXPOSE_GIT_REV': (
False,
'Display information about the running commit to non-superusers',
),
'FRONTEND_MIN_RETRY_TIME': (
2,
'Minimum number of seconds the front end waits before retrying a '
'failed request to the back end',
int,
),
'FRONTEND_MAX_RETRY_TIME': (
120,
'Maximum number of seconds the front end waits before retrying a '
'failed request to the back end',
int,
),
'MFA_ISSUER_NAME': (
'KoboToolbox',
'Issuer name displayed in multi-factor applications'
),
'MFA_ENABLED': (
True,
'Enable two-factor authentication'
),
'MFA_LOCALIZED_HELP_TEXT': (
LazyJSONSerializable({
'default': t(
'If you cannot access your authenticator app, please enter one '
'of your backup codes instead. If you cannot access those '
'either, then you will need to request assistance by '
'contacting [##support email##](mailto:##support email##).'
),
'some-other-language': (
'This will never appear because `some-other-language` is not '
'a valid language code, but this entry is here to show you '
'an example of adding another message in a different language.'
)
}),
(
'Guidance message presented when users click the '
'"Problems with the token" link.\n\n'
'`##support email##` is a placeholder for the `SUPPORT_EMAIL` '
'setting.\n'
'Markdown syntax is supported.\n'
'The “default” message will be used if no translations are provided.'
' The “default” should be in English.\n'
'To add messages in other languages, follow the example of '
'“some-other-language“, but replace “some-other-language“ with a '
'valid language code (e.g. “fr“ for French).'
),
# Use custom field for schema validation
'i18n_text_jsonfield_schema'
),
'SUPERUSER_AUTH_ENFORCEMENT': (
False,
'Require MFA for superusers with a usable password',
),
'ASR_MT_INVITEE_USERNAMES': (
'',
'List of invited usernames, one per line, who will have access to NLP '
'ASR/MT processing via external (costly) APIs.\nEnter * to invite '
'all users.'
),
'ASR_MT_GOOGLE_REQUEST_TIMEOUT': (
10,
(
'Timeout in seconds for google NLP data processing requests using'
' the operations API. '
)
),
'ASR_MT_GOOGLE_PROJECT_ID': (
'kobo-asr-mt',
'ID of the Google Cloud project used to access ASR/MT APIs',
),
'ASR_MT_GOOGLE_STORAGE_BUCKET_PREFIX': (
'kobo-asr-mt-tmp',
(
'Prefix for temporary ASR/MT files stored on Google Cloud. Useful'
' for lifecycle rules: files under this prefix can be deleted after'
' one day.\nThe bucket name itself is set by the environment'
' variable `GS_BUCKET_NAME`.'
),
),
'ASR_MT_GOOGLE_TRANSLATION_LOCATION': (
'us-central1',
(
'Google Cloud location to use for large translation tasks. It'
' cannot be `global`, and Google only allows certain locations.'
),
),
'ASR_MT_GOOGLE_CREDENTIALS': (
'',
'The JSON content of a private key file generated by the Google Cloud '
'IAM & Admin console.\nLeave blank to use a different Google '
'authentication mechanism.'
),
'USER_METADATA_FIELDS': (
LazyJSONSerializable([
{'name': 'name', 'required': True},
{'name': 'organization', 'required': False},
{'name': 'organization_type', 'required': False},
{'name': 'organization_website', 'required': False},
{'name': 'sector', 'required': False},
{'name': 'bio', 'required': False},
{'name': 'city', 'required': False},
{'name': 'country', 'required': False},
{'name': 'twitter', 'required': False},
{'name': 'linkedin', 'required': False},
{'name': 'instagram', 'required': False},
{'name': 'newsletter_subscription', 'required': False},
]),
# The available fields are hard-coded in the front end
'Display (and optionally require) these metadata fields for users.\n'
"Possible fields are:\n"
"'organization', 'organization_type', 'organization_website', 'sector', 'gender', 'bio', "
"'city', 'country', 'twitter', 'linkedin', 'instagram', and 'newsletter_subscription'.\n\n"
'To add another language, follow the example below.\n\n'
'{"name": "name", "required": False, "label": '
'{"default": "Full Name", "fr": "Nom Complet"}}\n'
"'default' is a required field within the 'label' dict, but 'label' is optional.",
# Use custom field for schema validation
'long_metadata_fields_jsonschema'
),
'PROJECT_METADATA_FIELDS': (
LazyJSONSerializable([
{'name': 'sector', 'required': False},
{'name': 'country', 'required': False},
{'name': 'description', 'required': False},
]),
# The available fields are hard-coded in the front end
'Display (and optionally require) these metadata fields for projects.\n'
"Possible fields are:\n"
"'sector', 'country', 'operational_purpose', 'collects_pii', "
"and 'description'\n\n"
'To add another language, follow the example below.\n\n'
'{"name": "sector", "required": False, "label": '
'{"default": "Sector", "fr": "Secteur"}}\n'
"'default' is a required field within the 'label' dict, but 'label' is optional.",
# Use custom field for schema validation
'metadata_fields_jsonschema'
),
'SECTOR_CHOICES': (
'\n'.join(s[0] for s in SECTOR_CHOICE_DEFAULTS),
"Options available for the 'sector' metadata field, one per line.",
'long_textfield'
),
'OPERATIONAL_PURPOSE_CHOICES': (
'',
"Options available for the 'operational purpose of data' metadata "
'field, one per line.'
),
'ORGANIZATION_INVITE_EXPIRY': (
14,
'Number of days before organization invites expire.',
'positive_int',
),
'ASSET_SNAPSHOT_DAYS_RETENTION': (
30,
'Number of days to keep asset snapshots',
'positive_int'
),
'IMPORT_TASK_DAYS_RETENTION': (
90,
'Number of days to keep import tasks',
'positive_int',
),
'FREE_TIER_THRESHOLDS': (
LazyJSONSerializable(FREE_TIER_NO_THRESHOLDS),
'Free tier thresholds: storage in kilobytes, '
'data (number of submissions), '
'minutes of transcription, '
'number of translation characters',
# Use custom field for schema validation
'free_tier_threshold_jsonschema',
),
'FREE_TIER_DISPLAY': (
LazyJSONSerializable(FREE_TIER_EMPTY_DISPLAY),
'Free tier frontend settings: name to use for the free tier, '
'array of text strings to display on the feature list of the Plans page',
'free_tier_display_jsonschema',
),
'FREE_TIER_CUTOFF_DATE': (
datetime(2050, 1, 1).date(),
'Users on the free tier who registered before this date will\n'
'use the custom plan defined by FREE_TIER_DISPLAY and FREE_TIER_LIMITS.',
),
'PROJECT_TRASH_GRACE_PERIOD': (
7,
'Number of days to keep projects in trash after users (soft-)deleted '
'them and before automatically hard-deleting them by the system',
'positive_int',
),
'ACCOUNT_TRASH_GRACE_PERIOD': (
30 * 6,
'Number of days to keep deactivated accounts in trash before '
'automatically hard-deleting all their projects and data.\n'
'Use -1 to require a superuser to empty the trash manually instead of '
'having the system empty it automatically.',
'positive_int_minus_one',
),
# Toggle for ZXCVBN
'ENABLE_PASSWORD_ENTROPY_METER': (
True,
'Display an entropy meter and password quality suggestions whenever users change their passwords.',
),
'ENABLE_PASSWORD_MINIMUM_LENGTH_VALIDATION': (
False,
'Enable minimum length validation',
),
'MINIMUM_PASSWORD_LENGTH': (
10,
'Minimum length for all passwords.',
int,
),
'ENABLE_PASSWORD_USER_ATTRIBUTE_SIMILARITY_VALIDATION': (
False,
'Enable user attribute similarity validation. '
'See `PASSWORD_USER_ATTRIBUTES` below for customization.',
),
'PASSWORD_USER_ATTRIBUTES': (
(
'username\n'
'full_name\n'
'email'
),
'List (one per line) all user attributes for similarity validation.\n'
"Possible attributes are 'username', 'full_name', 'email', 'organization'."
),
'ENABLE_COMMON_PASSWORD_VALIDATION': (
False,
'Enable common password validation.\n'
'To customize the list, go to Configuration file section and add common password file.\n'
'Django default list is based on https://tinyurl.com/django3-2-common-passwords.',
),
'ENABLE_PASSWORD_CUSTOM_CHARACTER_RULES_VALIDATION': (
False,
'Enable custom character rules',
),
'PASSWORD_CUSTOM_CHARACTER_RULES': (
(
'[[:lower:]]\n'
'[[:upper:]]\n'
'\d\n'
'[\W_]'
),
'List all custom character rules as regular expressions supported '
'by `regex` python library.\n'
'One per line.',
),
'PASSWORD_CUSTOM_CHARACTER_RULES_REQUIRED_TO_PASS': (
3,
'The minimum number of character rules to pass.',
int,
),
'ENABLE_MOST_RECENT_PASSWORD_VALIDATION': (
False,
'Enable most recent password validation which will prevent the user from '
'reusing the most recent password.',
),
'ENABLE_CUSTOM_PASSWORD_GUIDANCE_TEXT': (
False,
'Enable custom password guidance text to help users create their passwords.',
),
'CUSTOM_PASSWORD_GUIDANCE_TEXT': (
LazyJSONSerializable(
{
'default': t(
'The password must be at least 10 characters long and'
' contain 3 or more of the following: uppercase letters,'
' lowercase letters, numbers, and special characters. It'
' cannot be similar to your name, username, or email'
' address.'
),
'some-other-language': (
'This will never appear because `some-other-language` is'
' not a valid language code, but this entry is here to show'
' you an example of adding another message in a different'
' language.'
),
}
),
(
'Guidance message presented when users create or modify a password. '
'It should reflect the defined password rules.\n\n'
'Markdown syntax is supported.\n'
'The “default” message will be used if no translations are provided.'
' The “default” should be in English.\n'
'To add messages in other languages, follow the example of '
'“some-other-language“, but replace “some-other-language“ with a '
'valid language code (e.g. “fr“ for French).'
),
'i18n_text_jsonfield_schema',
),
'PROJECT_OWNERSHIP_RESUME_THRESHOLD': (
10,
'Number of minutes asynchronous tasks can be idle before being '
'restarted.\n'
'It is recommended to keep greater than 10 minutes.',
'positive_int',
),
'PROJECT_OWNERSHIP_STUCK_THRESHOLD': (
12 * 60,
(
'Number of minutes asynchronous tasks can run before being '
'flagged as failed.\n'
'Should be greater than `PROJECT_OWNERSHIP_RESUME_THRESHOLD`.'
),
'positive_int',
),
'PROJECT_OWNERSHIP_INVITE_EXPIRY': (
14,
'Number of days before invites expire.',
'positive_int',
),
'PROJECT_OWNERSHIP_INVITE_HISTORY_RETENTION': (
30,
(
'Number of days to keep invites history.\n'
'Failed invites are kept forever.'
),
'positive_int',
),
'PROJECT_OWNERSHIP_IN_APP_MESSAGES_EXPIRY': (
7,
'The number of days after which in-app messages expire.',
'positive_int',
),
'PROJECT_OWNERSHIP_AUTO_ACCEPT_INVITES': (
False,
'Auto-accept invites by default and do not sent them by e-mail.'
),
'PROJECT_OWNERSHIP_ADMIN_EMAIL': (
'',
(
'Email addresses to which error reports are sent, one per line.\n'
'Leave empty to not send emails.'
),
),
'PROJECT_OWNERSHIP_ADMIN_EMAIL_SUBJECT': (
'KoboToolbox Notifications: Project ownership transfer failure',
'Email subject to sent to admins on failure.',
),
'PROJECT_OWNERSHIP_ADMIN_EMAIL_BODY': (
(
'Dear admins,\n\n'
'A transfer of project ownership has failed:\n'
'##invite_url##'
),
'Email message to sent to admins on failure.',
),
'PROJECT_HISTORY_LOG_LIFESPAN': (
60,
'Length of time days to keep project history logs.',
'positive_int',
),
'ACCESS_LOG_LIFESPAN': (
60,
'Length of time in days to keep access logs.',
'positive_int',
),
'USE_TEAM_LABEL': (
True,
'Use the term "Team" instead of "Organization" when Stripe is not enabled',
),
}
CONSTANCE_ADDITIONAL_FIELDS = {
'free_tier_threshold_jsonschema': [
'kpi.fields.jsonschema_form_field.FreeTierThresholdField',
{'widget': 'django.forms.Textarea'},
],
'free_tier_display_jsonschema': [
'kpi.fields.jsonschema_form_field.FreeTierDisplayField',
{'widget': 'django.forms.Textarea'},
],
'i18n_text_jsonfield_schema': [
'kpi.fields.jsonschema_form_field.I18nTextJSONField',
{'widget': 'django.forms.Textarea'},
],
'long_metadata_fields_jsonschema': [
'kpi.fields.jsonschema_form_field.UserMetadataFieldsListField',
{
'widget': 'django.forms.Textarea',
'widget_kwargs': {
'attrs': {'rows': 45}
}
},
],
'long_textfield': [
'django.forms.fields.CharField',
{
'widget': 'django.forms.Textarea',
'widget_kwargs': {
'attrs': {'rows': 30}
}
},
],
'metadata_fields_jsonschema': [
'kpi.fields.jsonschema_form_field.MetadataFieldsListField',
{'widget': 'django.forms.Textarea'},
],
'positive_int': ['django.forms.fields.IntegerField', {
'min_value': 0
}],
'positive_int_minus_one': ['django.forms.fields.IntegerField', {
'min_value': -1
}],
'positive_int': ['django.forms.fields.IntegerField', {
'min_value': 0
}],
}
CONSTANCE_CONFIG_FIELDSETS = {
'General Options': (
'REGISTRATION_OPEN',
'REGISTRATION_ALLOWED_EMAIL_DOMAINS',
'REGISTRATION_DOMAIN_NOT_ALLOWED_ERROR_MESSAGE',
'TERMS_OF_SERVICE_URL',
'PRIVACY_POLICY_URL',
'SOURCE_CODE_URL',
'SUPPORT_EMAIL',
'SUPPORT_URL',
'COMMUNITY_URL',
'SYNCHRONOUS_EXPORT_CACHE_MAX_AGE',
'EXPOSE_GIT_REV',
'FRONTEND_MIN_RETRY_TIME',
'FRONTEND_MAX_RETRY_TIME',
'USE_TEAM_LABEL',
'ACCESS_LOG_LIFESPAN',
'PROJECT_HISTORY_LOG_LIFESPAN',
'ORGANIZATION_INVITE_EXPIRY'
),
'Rest Services': (
'ALLOW_UNSECURED_HOOK_ENDPOINTS',
'HOOK_MAX_RETRIES',
),
'Natural language processing': (
'ASR_MT_INVITEE_USERNAMES',
'ASR_MT_GOOGLE_PROJECT_ID',
'ASR_MT_GOOGLE_STORAGE_BUCKET_PREFIX',
'ASR_MT_GOOGLE_TRANSLATION_LOCATION',
'ASR_MT_GOOGLE_CREDENTIALS',
'ASR_MT_GOOGLE_REQUEST_TIMEOUT',
),
'Security': (
'SSRF_ALLOWED_IP_ADDRESS',
'SSRF_DENIED_IP_ADDRESS',
'MFA_ISSUER_NAME',
'MFA_ENABLED',
'MFA_LOCALIZED_HELP_TEXT',
'SUPERUSER_AUTH_ENFORCEMENT',
),
'Metadata options': (
'USER_METADATA_FIELDS',
'PROJECT_METADATA_FIELDS',
'SECTOR_CHOICES',
'OPERATIONAL_PURPOSE_CHOICES',
),
'Password Validation': (
'ENABLE_PASSWORD_ENTROPY_METER',
'ENABLE_PASSWORD_MINIMUM_LENGTH_VALIDATION',
'ENABLE_PASSWORD_USER_ATTRIBUTE_SIMILARITY_VALIDATION',
'ENABLE_COMMON_PASSWORD_VALIDATION',
'ENABLE_PASSWORD_CUSTOM_CHARACTER_RULES_VALIDATION',
'ENABLE_MOST_RECENT_PASSWORD_VALIDATION',
'ENABLE_CUSTOM_PASSWORD_GUIDANCE_TEXT',
'MINIMUM_PASSWORD_LENGTH',
'PASSWORD_USER_ATTRIBUTES',
'PASSWORD_CUSTOM_CHARACTER_RULES',
'PASSWORD_CUSTOM_CHARACTER_RULES_REQUIRED_TO_PASS',
'CUSTOM_PASSWORD_GUIDANCE_TEXT',
),
'Transfer project ownership': (
'PROJECT_OWNERSHIP_RESUME_THRESHOLD',
'PROJECT_OWNERSHIP_STUCK_THRESHOLD',
'PROJECT_OWNERSHIP_INVITE_HISTORY_RETENTION',
'PROJECT_OWNERSHIP_INVITE_EXPIRY',
'PROJECT_OWNERSHIP_IN_APP_MESSAGES_EXPIRY',
'PROJECT_OWNERSHIP_ADMIN_EMAIL',
'PROJECT_OWNERSHIP_ADMIN_EMAIL_SUBJECT',
'PROJECT_OWNERSHIP_ADMIN_EMAIL_BODY',
'PROJECT_OWNERSHIP_AUTO_ACCEPT_INVITES',
),
'Trash bin': (
'ACCOUNT_TRASH_GRACE_PERIOD',
'PROJECT_TRASH_GRACE_PERIOD',
),
'Regular maintenance settings': (
'ASSET_SNAPSHOT_DAYS_RETENTION',
'IMPORT_TASK_DAYS_RETENTION',
),
'Tier settings': (
'FREE_TIER_THRESHOLDS',
'FREE_TIER_DISPLAY',
'FREE_TIER_CUTOFF_DATE',
),
}
# Tell django-constance to use a database model instead of Redis
CONSTANCE_BACKEND = 'kobo.apps.constance_backends.database.DatabaseBackend'
CONSTANCE_DATABASE_CACHE_BACKEND = 'default'
# Warn developers to use `pytest` instead of `./manage.py test`
class DoNotUseRunner:
def __init__(self, *args, **kwargs):
raise NotImplementedError('Please run tests with `pytest` instead')
TEST_RUNNER = __name__ + '.DoNotUseRunner'
# The backend that handles user authentication must match KoBoCAT's when
# sharing sessions. ModelBackend does not interfere with object-level
# permissions: it always denies object-specific requests (see
# https://github.com/django/django/blob/1.7/django/contrib/auth/backends.py#L44).
# KoBoCAT also lists ModelBackend before
# guardian.backends.ObjectPermissionBackend.
AUTHENTICATION_BACKENDS = (
'kpi.backends.ModelBackend',
'kpi.backends.ObjectPermissionBackend',
'allauth.account.auth_backends.AuthenticationBackend',
'kobo.apps.openrosa.libs.backends.ObjectPermissionBackend',
)
ROOT_URLCONF = 'kobo.urls'
WSGI_APPLICATION = 'kobo.wsgi.application'
# What User object should be mapped to AnonymousUser?
ANONYMOUS_USER_ID = -1
# Permissions assigned to AnonymousUser are restricted to the following
ALLOWED_ANONYMOUS_PERMISSIONS = (
'kpi.view_asset',
'kpi.discover_asset',
'kpi.add_submissions',
'kpi.view_submissions',
)
# run heavy migration scripts by default
# NOTE: this should be set to False for major deployments. This can take a long time
SKIP_HEAVY_MIGRATIONS = env.bool('SKIP_HEAVY_MIGRATIONS', False)
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': env.db_url(
'KPI_DATABASE_URL' if 'KPI_DATABASE_URL' in os.environ else 'DATABASE_URL',
default='sqlite:///%s/db.sqlite3' % BASE_DIR
),
}
OPENROSA_DB_ALIAS = 'kobocat'
if 'KC_DATABASE_URL' in os.environ:
DATABASES[OPENROSA_DB_ALIAS] = env.db_url('KC_DATABASE_URL')
DATABASE_ROUTERS = ['kpi.db_routers.DefaultDatabaseRouter']
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
django.conf.locale.LANG_INFO.update(EXTRA_LANG_INFO)
DJANGO_LANGUAGE_CODES = env.str(
'DJANGO_LANGUAGE_CODES',
default=(
'am ' # Amharic
'ar ' # Arabic
'bn ' # Bengali
'cs ' # Czech
'de ' # German
'en ' # English
'es ' # Spanish
'fa ' # Persian/Farsi
'fr ' # French
'hi ' # Hindi
'hu ' # Hungarian
'id ' # Indonesian
'ja ' # Japanese
'km ' # Khmer
'ku ' # Kurdish
'ln ' # Lingala
'my ' # Burmese/Myanmar
'ny ' # Chewa/Chichewa/Nyanja
'ne ' # Nepali
'pl ' # Polish
'pt ' # Portuguese
'ru ' # Russian
'sw ' # Swahili
'th ' # Thai
'tr ' # Turkish
'uk ' # Ukrainian
'vi ' # Vietnamese
'yo ' # Yoruba
'zh-hans' # Chinese Simplified
)
)
LANGUAGES = [
(lang_code, get_language_info(lang_code)['name_local'])
for lang_code in DJANGO_LANGUAGE_CODES.split(' ')
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
USE_I18N = True
USE_TZ = True
CAN_LOGIN_AS = lambda request, target_user: request.user.is_superuser
# Impose a limit on the number of records returned by the submission list
# endpoint. This overrides any `?limit=` query parameter sent by a client
SUBMISSION_LIST_LIMIT = 30000
# uWSGI, NGINX, etc. allow only a limited amount of time to process a request.
# Set this value to match their limits
SYNCHRONOUS_REQUEST_TIME_LIMIT = 120 # seconds
# REMOVE the oldest if a user exceeds this many exports for a particular form
MAXIMUM_EXPORTS_PER_USER_PER_FORM = 10
# Private media file configuration
PRIVATE_STORAGE_ROOT = os.path.join(BASE_DIR, 'media')
PRIVATE_STORAGE_AUTH_FUNCTION = \
'kpi.utils.private_storage.superuser_or_username_matches_prefix'
# django-markdownx, for in-app messages
MARKDOWNX_UPLOAD_URLS_PATH = reverse_lazy('markdownx-uploader-image-upload')
MARKDOWNX_UPLOAD_CONTENT_TYPES = [
'image/jpeg',
'image/png',
'image/svg+xml',
'image/gif',
'image/webp',
]
# Github-flavored Markdown from `py-gfm`,
# ToDo Uncomment when it's compatible with Markdown 3.x
# MARKDOWNX_MARKDOWN_EXTENSIONS = ['mdx_gfm']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/' + os.environ.get('KPI_MEDIA_URL', 'media').strip('/') + '/'
# `PUBLIC_MEDIA_PATH` sets the `upload_to` attribute of explicitly-public
# `FileField`s, e.g. in `ConfigurationFile`. The corresponding location on the
# file system (usually `MEDIA_ROOT + PUBLIC_MEDIA_PATH`) should be exposed to
# everyone via NGINX. For more information, see
# https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to
PUBLIC_MEDIA_PATH = '__public/'
# Following the uWSGI mountpoint convention, this should have a leading slash
# but no trailing slash
KPI_PREFIX = env.str('KPI_PREFIX', 'False')
if KPI_PREFIX.lower() == 'false':
KPI_PREFIX = False
else:
KPI_PREFIX = '/' + KPI_PREFIX.strip('/')
# KPI_PREFIX should be set in the environment when running in a subdirectory
if KPI_PREFIX and KPI_PREFIX != '/':
STATIC_URL = KPI_PREFIX + '/' + STATIC_URL.lstrip('/')
MEDIA_URL = KPI_PREFIX + '/' + MEDIA_URL.lstrip('/')
LOGIN_URL = KPI_PREFIX + '/' + global_settings.LOGIN_URL.lstrip('/')
LOGIN_REDIRECT_URL = KPI_PREFIX + '/' + LOGIN_REDIRECT_URL.lstrip('/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'jsapp'),
os.path.join(BASE_DIR, 'static'),
)
if os.path.exists(os.path.join(BASE_DIR, 'dkobo', 'jsapp')):
STATICFILES_DIRS = STATICFILES_DIRS + (
os.path.join(BASE_DIR, 'dkobo', 'jsapp'),
os.path.join(BASE_DIR, 'dkobo', 'dkobo', 'static'),
)
REST_FRAMEWORK = {
'URL_FIELD_NAME': 'url',
'DEFAULT_PAGINATION_CLASS': 'kpi.paginators.Paginated',
'PAGE_SIZE': 100,
'DEFAULT_AUTHENTICATION_CLASSES': [
# SessionAuthentication and BasicAuthentication would be included by
# default
'kpi.authentication.SessionAuthentication',
'kpi.authentication.BasicAuthentication',
'kpi.authentication.TokenAuthentication',
'kpi.authentication.OAuth2Authentication',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'kpi.renderers.XMLRenderer',
],
'DEFAULT_VERSIONING_CLASS': 'kpi.versioning.APIAutoVersioning',
# Cannot be placed in kpi.exceptions.py because of circular imports
'EXCEPTION_HANDLER': 'kpi.utils.drf_exceptions.custom_exception_handler',
}
OPENROSA_REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': None,
'DEFAULT_VERSIONING_CLASS': None,
# deprecated
# # Use hyperlinked styles by default.
# # Only used if the `serializer_class` attribute is not set on a view.
# 'DEFAULT_MODEL_SERIALIZER_CLASS': (
# 'rest_framework.serializers.HyperlinkedModelSerializer'
# ),
# # Use Django's standard `django.contrib.auth` permissions,
# # or allow read-only access for unauthenticated users.
# 'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.AllowAny',
# ],
'DEFAULT_AUTHENTICATION_CLASSES': [
'kpi.authentication.DigestAuthentication',
'kpi.authentication.OAuth2Authentication',
'kpi.authentication.TokenAuthentication',
# HttpsOnlyBasicAuthentication must come before SessionAuthentication because
# Django authentication is called before DRF authentication and users get authenticated with
# Session if it comes first (which bypass BasicAuthentication and MFA validation)
'kobo.apps.openrosa.libs.authentication.HttpsOnlyBasicAuthentication',
'kpi.authentication.SessionAuthentication',
],
'DEFAULT_RENDERER_CLASSES': [
# Keep JSONRenderer at the top "in order to send JSON responses to
# clients that do not specify an Accept header." See
# http://www.django-rest-framework.org/api-guide/renderers/#ordering-of-renderer-classes
'rest_framework.renderers.JSONRenderer',
'rest_framework_jsonp.renderers.JSONPRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework_xml.renderers.XMLRenderer',
'rest_framework_csv.renderers.CSVRenderer',
],
# FIXME Kobocat migration: Move to main REST_FRAMEWORK and change logic to handle kobocat view properly
'VIEW_NAME_FUNCTION': 'kobo.apps.openrosa.apps.api.tools.get_view_name',
'VIEW_DESCRIPTION_FUNCTION': 'kobo.apps.openrosa.apps.api.tools.get_view_description',
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {