summaryrefslogtreecommitdiff
path: root/example_project/settings.py
blob: 709fce8ea892037635568a409cf530b0853be702 (plain)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Django settings for ishtar project.

import os
import sys
from importlib import import_module
from ishtar_common.version import get_version

try:
    import sentry_sdk
    from sentry_sdk.integrations.celery import CeleryIntegration
    from sentry_sdk.integrations.django import DjangoIntegration
except ImportError:
    sentry_sdk = None

DEBUG = False
DEBUG_TOOLBAR = False
DEBUG_TO_CONSOLE = False
SQL_DEBUG = False
DJANGO_EXTENSIONS = False
TEST_VIEWS = True
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"

if "test" in sys.argv:
    sys.path.insert(0, "..")

IMAGE_MAX_SIZE = None  # put x, y for resizing
THUMB_MAX_SIZE = (600, 600)

# DISABLE_TASK_TIMEOUT = False  # problematic for now
DISABLE_TASK_TIMEOUT = True
CACHE_TASK_TIMEOUT = 4
CACHE_SMALLTIMEOUT = 60
CACHE_TIMEOUT = 3600
CACHE_LONGTIMEOUT = 3600 * 6
CACHE_BACKEND = "memcached://127.0.0.1:11211/"

SEP = os.path.sep
ROOT_PATH = SEP.join(os.path.abspath(__file__).split(SEP)[:-1]) + SEP
STATIC_URL = "/static/"
STATIC_ROOT = ROOT_PATH + "static/"
BASE_URL = "/"
URL_PATH = ""
EXTRA_VERSION = "git"

LOCALE_PATHS = [os.path.abspath(os.path.join(ROOT_PATH, "..", "locale"))]

STATICFILES_FINDERS = (
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "compressor.finders.CompressorFinder",
)

BS_STATIC = ROOT_PATH + "../bootstrap_datepicker/static"
if not os.path.exists(BS_STATIC):
    BS_STATIC = "/usr/lib/python3/dist-packages/bootstrap_datepicker/static"

STATICFILES_DIRS = (BS_STATIC,)

ODT_TEMPLATE = ROOT_PATH + "../ishtar_common/static/template.odt"

LOGIN_REDIRECT_URL = "/" + URL_PATH
LOGOUT_REDIRECT_URL = "/" + URL_PATH

ACCOUNT_ACTIVATION_DAYS = 7

PASSWORD_HASHERS = [
    'ishtar_common.utils.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

# change this in local_settings
DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "ishtar",
        "USER": "ishtar",
        "PASSWORD": "ishtar",
        "HOST": "127.0.0.1",
        "PORT": "5432",
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = "Europe/Paris"

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "fr-fr"

COUNTRY = "fr"

OOOK_DATE_FORMAT = "%-d %B %Y"
OOO_DATE_FORMAT = "%-d %B %Y"
DATE_FORMAT = "%-d %B %Y"

SITE_ID = 1

USE_TZ = True

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
USE_THOUSAND_SEPARATOR = True
LANGUAGES = (
    ("fr", "Français"),
    ("en", "English"),
)
DEFAULT_LANGUAGE = 1
STORAGES = {
    "default": {"BACKEND": "ishtar_common.utils.IshtarFileSystemStorage"},
    "staticfiles": {
        "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
    },
}

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ROOT_PATH + "media/"

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = "/media/"

MIDDLEWARE = [
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "axes.middleware.AxesMiddleware",
]

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(ROOT_PATH, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "ishtar_common.context_processors.get_base_context",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.csrf",
            ],
        },
    },
]


ROOT_URLCONF = "example_project.urls"

AUTHENTICATION_BACKENDS = (
    "axes.backends.AxesBackend",
    "ishtar_common.backend.ObjectPermBackend",
    "guardian.backends.ObjectPermissionBackend",
)

INSTALLED_APPS = [
    "django_registration",
    "ishtar_common",
    "archaeological_files",
    "archaeological_operations",
    "archaeological_context_records",
    "archaeological_warehouse",
    "archaeological_finds",
    "compressor",
    "axes",
    "rest_framework",
    "rest_framework.authtoken",
    "django.contrib.auth",
    "django.contrib.admin",
    "django.contrib.contenttypes",
    "django.contrib.postgres",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.gis",
    "django.contrib.staticfiles",
    "django.contrib.messages",
    "django.contrib.humanize",
    "guardian",
    # 'debug_toolbar',
]

USE_TRANSLATION_OVERLOAD = False
TRANSLATION_OVERLOAD_DEBUG = False

SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 5 * 24 * 60 * 60
AXES_ENABLED = False
AXES_FAILURE_LIMIT = 5
AXES_COOLOFF_TIME = 2  # hours
AXES_RESET_ON_SUCCESS = True

MAIN_APP = ""

LOG_FILE = ""
LOG_LEVEL = ""

default_handler = {"handlers": ["logfile"], "level": "INFO", "propogate": False}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        # Include the default Django email handler for errors
        # This is what you'd get without configuring logging at all.
        "mail_admins": {
            "class": "django.utils.log.AdminEmailHandler",
            "level": "ERROR",
            # But the emails are plain text by default - HTML is nicer
            "include_html": True,
        },
        # Log to a text file that can be rotated by logrotate
        "logfile": {
            "class": "logging.handlers.WatchedFileHandler",
            "filename": "/var/log/django/ishtar.log",
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "django.request": {
            "handlers": ["mail_admins", "logfile"],
            "level": "ERROR",
            "propagate": True,
        },
        "django": {
            "handlers": ["logfile"],
            "level": "ERROR",
            "propagate": False,
        },
        "django.server": {
            "handlers": ["console"],
            "level": "INFO",
            "propagate": False,
        },
        "django.security.DisallowedHost": {
            "handlers": ["logfile"],
            "propagate": False,
        },
        "ishtar_pdl": default_handler,
        "ishtar_common": default_handler,
        "archaeological_files": default_handler,
        "archaeological_operations": default_handler,
        "archaeological_context_records": default_handler,
        "archaeological_warehouse": default_handler,
        "archaeological_finds": default_handler,
    },
}

USE_BACKGROUND_TASK = False
USE_LIBREOFFICE = False
LIBREOFFICE_PORT = 8101
LIBREOFFICE_HOST = "localhost"

# Ishtar custom

ISHTAR_FEED_URL = "https://discourse.ishtar-archeo.net/latest.rss"
ISHTAR_MAP_MAX_ITEMS = 50000
ISHTAR_QRCODE_VERSION = 6  # density of the QR code
ISHTAR_QRCODE_SCALE = 5  # scale of the QR code
ISHTAR_DEFAULT_YEAR = 1900
ISHTAR_MUSEUM_GAM = False  # France - AlimGAM export of exhibitions
# exclude business days from deadline calculation
ISHTAR_FILE_EXCLUDE_BUSSINESS_DAYS = True
# timeout for request token (GIS connector)
ISHTAR_REQUEST_TOKEN_TIMEOUT = 60 * 5  # 5 minutes
ISHTAR_SLUGS = {
    "document-publisher": ["publisher"],
}

ISHTAR_MIGRATE_V4 = False
ISHTAR_DOCUMENT_VERSION = "develop-4.4"

REGISTRATION_OPEN = False
SRID = 4326  # WGS84 - World
SURFACE_SRID = 4326  # WGS84 - World
ENCODING = "windows-1252"
ALT_ENCODING = "ISO-8859-15"
APP_NAME = "SRA - Pays de la Loire"
SURFACE_UNIT = "square-metre"
SURFACE_UNIT_LABEL = "m²"
JOINT = " | "
# dir for ishtar maintenance script - as it can be a serious security issue if
# not managed cautiously the dir contening these scripts is not set by default
ISHTAR_SCRIPT_DIR = ""

# GDPR
GDPR_LOGGING = False
GDPR_RETENTION_PERIOD = int(30.5 * 6) + 1  # ~ 6 month of logging

# TODO: clean...
ISHTAR_FILE_PREFIX = ""
# string len of find indexes - i.e: find with index 42 will be 00042
ISHTAR_FINDS_INDEX_ZERO_LEN = 5
# DB key: txt_idx
ISHTAR_PERIODS = {}
ISHTAR_PERMIT_TYPES = {}
ISHTAR_DOC_TYPES = {"undefined": "Undefined"}

# number of days for password expiration: None for no expiration
ISHTAR_PASSWORD_EXPIRATION_DAYS = None
ISHTAR_SEARCH_LANGUAGE = "french"
ISHTAR_SECURE = True
ISHTAR_SECURE_OPTIONS = False
ISHTAR_STRONG_PASSWORD_POLICY = False
ISHTAR_DPTS = []

MAX_ATTEMPTS = 1  # django background tasks

MAX_UPLOAD_SIZE = 100  # in Mo
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10240

# path to the "dot" program to generate graph
DOT_BINARY = "/usr/bin/dot"
PDFTOPPM_BINARY = ""

UNOCONV_BINARY = "/usr/bin/unoconv"

TEST_RUNNER = "ishtar_common.tests.ManagedModelTestRunner"
SELENIUM_TEST = False
CELERY_BROKER_URL = ""
SENTRY_ID = None
DISTRIBUTION = "source"
LIB_BASE_PATH = ROOT_PATH + "../"
FIXTURE_AUTH_PATH = ROOT_PATH + "../"
SHARE_BASE_PATH = FIXTURE_AUTH_PATH

AUTH_PASSWORD_VALIDATORS = []

try:
    from local_settings import *
except ImportError as e:
    try:
        from .local_settings import *
    except ImportError as e:
        print("Unable to load local_settings.py:", e)

try:
    from custom_settings import *
except ImportError:
    pass

if USE_TRANSLATION_OVERLOAD:
    INSTALLED_APPS.insert(0, "overload_translation")

if "SECRET_KEY" not in globals():  # explicit import from the root for celery
    current_path = os.path.abspath(__file__)
    current_dir_path = os.path.dirname(current_path).split(os.sep)[-1]
    my_module = import_module(current_dir_path + ".local_settings")
    module_dict = my_module.__dict__
    try:
        to_import = my_module.__all__
    except AttributeError:
        to_import = [name for name in module_dict if not name.startswith("_")]
    globals().update({name: module_dict[name] for name in to_import})

if LANGUAGE_CODE == "fr-fr" and SRID == 4326:
    SRID = 27572  # Lambert zone II - France
    SURFACE_SRID = 2154  # Lambert 93 - France

TABLE_COLS = {}  # allow to overload table col settings on extra module
COL_LABELS = {}

if MAIN_APP:
    INSTALLED_APPS.insert(INSTALLED_APPS.index("ishtar_common"), MAIN_APP)
    extra_module = import_module(MAIN_APP + ".extra_settings")
    if hasattr(extra_module, "TABLE_COLS"):
        TABLE_COLS = extra_module.TABLE_COLS
    if hasattr(extra_module, "COL_LABELS"):
        COL_LABELS = extra_module.COL_LABELS

TESTING = sys.argv[1:2] == ["test"]

PROJECT_SLUG = locals().get("PROJECT_SLUG", "default")

if LOG_FILE:
    LOGGING["handlers"]["logfile"]["filename"] = LOG_FILE
elif DEBUG and EXTRA_VERSION != "debian":
    LOGGING["handlers"]["logfile"]["filename"] = (
            ROOT_PATH + "log-" + PROJECT_SLUG + ".log"
    )
else:
    LOGGING["handlers"]["logfile"]["filename"] = (
        "/var/log/django/ishtar-" + PROJECT_SLUG + ".log"
    )

INTERNAL_IPS = ("127.0.0.1",)

JQUERY_URL = STATIC_URL + "js/jquery.min.js"
JQUERY_UI_URL = STATIC_URL + "js/jquery-ui/"

if DEBUG and not LOG_FILE:
    # make all loggers use the console
    for logger in LOGGING["loggers"]:
        if DEBUG_TO_CONSOLE:
            LOGGING["loggers"][logger]["handlers"] = ["console"]
        elif "console" not in LOGGING["loggers"][logger]["handlers"]:
            LOGGING["loggers"][logger]["handlers"] += ["console"]

if LOG_LEVEL:
    for logger in LOGGING["loggers"]:
        LOGGING["loggers"][logger]["level"] = LOG_LEVEL
        if logger.startswith("archaeological") or logger.startswith("ishtar"):
            LOGGING["loggers"][logger]["level"] = LOG_LEVEL

CELERY_DEFAULT_QUEUE = "celery"

if USE_BACKGROUND_TASK:
    if not CELERY_BROKER_URL:
        CELERY_BROKER_URL = "amqp://localhost"

if DJANGO_EXTENSIONS:
    INSTALLED_APPS.append("django_extensions")

if DEBUG_TOOLBAR:
    if ".." not in sys.path:
        sys.path.insert(0, "..")
    global DEBUG_TOOLBAR_PANELS
    global DEBUG_TOOLBAR_CONFIG
    MIDDLEWARE.insert(len(MIDDLEWARE) - 1, "debug_toolbar.middleware.DebugToolbarMiddleware")
    INSTALLED_APPS += ["debug_toolbar"]
    DEBUG_TOOLBAR_PANELS = (
        "debug_toolbar.panels.versions.VersionsPanel",
        "debug_toolbar.panels.timer.TimerPanel",
        "debug_toolbar.panels.settings.SettingsPanel",
        "debug_toolbar.panels.headers.HeadersPanel",
        "debug_toolbar.panels.request.RequestPanel",
        "debug_toolbar.panels.sql.SQLPanel",
        "debug_toolbar.panels.staticfiles.StaticFilesPanel",
        "debug_toolbar.panels.templates.TemplatesPanel",
        "debug_toolbar.panels.cache.CachePanel",
        "debug_toolbar.panels.signals.SignalsPanel",
        "debug_toolbar.panels.logging.LoggingPanel",
        "debug_toolbar.panels.redirects.RedirectsPanel",
    )
    DEBUG_TOOLBAR_CONFIG = {"INTERCEPT_REDIRECTS": False}


if SQL_DEBUG:
    LOGGING["loggers"]["django.db.backends"] = {
        "level": "DEBUG",
        "handlers": ["console"],
    }

if "test" in sys.argv:
    PROJECT_SLUG += "-test"

if not DEBUG:
    # persistent connection
    DATABASES["default"]["CONN_MAX_AGE"] = 600


def filter_irrelevant_errors(event, hint):
    if event.get("logger", None) == "django.security.DisallowedHost":
        return None
    return event


if SENTRY_ID and sentry_sdk:
    sentry_integrations = [DjangoIntegration()]
    if USE_BACKGROUND_TASK:
        sentry_integrations.append(CeleryIntegration())
    sentry_sdk.init(
        dsn=SENTRY_ID,
        integrations=sentry_integrations,
        before_send=filter_irrelevant_errors,
        send_default_pii=True,
        release=get_version() + "-" + EXTRA_VERSION
    )


if ISHTAR_SECURE_OPTIONS:
    AXES_ENABLED = True  # log logging attempts and block account on many fails
    # verify https is ok before activating
    MIDDLEWARE = MIDDLEWARE[:-1] + [
        "django.middleware.security.SecurityMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
    ] + [MIDDLEWARE[-1]]
    SECURE_HSTS_SECONDS = 31536000
    SECURE_HSTS_PRELOAD = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    X_FRAME_OPTIONS = "DENY"

if ISHTAR_STRONG_PASSWORD_POLICY and not AUTH_PASSWORD_VALIDATORS:
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
            'OPTIONS': {
                'min_length': 12,
            }
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'ishtar_common.utils.EachCharacterTypeValidator',
        },
    ]

if not AUTH_PASSWORD_VALIDATORS:
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
            'OPTIONS': {
                'min_length': 8,
            }
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
    ]