Gitlab CSE Unil

base.py 14 KB
Newer Older
1
# *-* encoding: utf-8 *-*
2
"""Common settings and globals."""
Julien Furrer's avatar
Julien Furrer committed
3
from __future__ import unicode_literals
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
from os.path import abspath, basename, dirname, join, normpath
from sys import path, modules
from django.core.exceptions import ImproperlyConfigured


# ========== PATH CONFIGURATION
#
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))

# Absolute filesystem path to the top-level project folder:
SITE_ROOT = dirname(DJANGO_ROOT)

# Site name:
SITE_NAME = basename(DJANGO_ROOT)

# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)
# ---------- END PATH CONFIGURATION


# ========== LOAD SECRETS
try:
    from .components.private import *
except ImportError:
    raise ImproperlyConfigured("Unable to load private configuration. "
                               "Please add a SECRET_KEY in {}/settings/components/private.py".format(SITE_NAME))


# ========== DJANGO GENERAL CONFIGURATIONS
#
# ..... MANAGEMENT
DEBUG = False
ALLOWED_HOSTS = []
ADMINS = (
M. Chardon's avatar
M. Chardon committed
40
    ("Admin Riset", 'riset-admin@unil.ch')
41
42
43
44
45
46
47
48
)
MANAGERS = ADMINS

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
M. Chardon's avatar
M. Chardon committed
49
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
50
    'django.contrib.messages.middleware.MessageMiddleware',
M. Chardon's avatar
M. Chardon committed
51
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
52
53
54
55
56
57
58
59
60
61
62
63
64
)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}


# ..... TEMPLATES CONFIG
TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
Julien Furrer's avatar
Julien Furrer committed
65
    'DIRS': (normpath(join(SITE_ROOT, 'templates')), ),
66
    'OPTIONS': {
M. Chardon's avatar
M. Chardon committed
67
        'debug': DEBUG,
68
69
70
71
72
73
        'loaders': (
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader'
        ),
        'context_processors': [
            'django.contrib.auth.context_processors.auth',
M. Chardon's avatar
M. Chardon committed
74
75
76
77
78
79
            'django.template.context_processors.debug',
            'django.template.context_processors.i18n',
            'django.template.context_processors.media',
            'django.template.context_processors.static',
            'django.template.context_processors.request',
            'django.template.context_processors.tz',
80
            'django.contrib.messages.context_processors.messages',
Julien Furrer's avatar
Julien Furrer committed
81
            'adim_utils.context_processors.default',
82
83
84
85
86
87
        ],
        'string_if_invalid': "",
    }
}]

# backward compatibility
M. Chardon's avatar
M. Chardon committed
88
89
90
91
92
#TEMPLATE_DIRS = TEMPLATES[0]['DIRS']
#TEMPLATE_CONTEXT_PROCESSORS = TEMPLATES[0]['OPTIONS']['context_processors']
#TEMPLATE_DEBUG = TEMPLATES[0]['OPTIONS']['debug']
#TEMPLATE_LOADERS = TEMPLATES[0]['OPTIONS']['loaders']
#TEMPLATE_STRING_IF_INVALID = TEMPLATES[0]['OPTIONS']['string_if_invalid']
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


# ..... MEDIA AND STATICS PATHS
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))
STATIC_ROOT = normpath(join(SITE_ROOT, 'static'))


# ..... Localization
LANGUAGE_CODE = 'fr-ch'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1


# ..... Application
ROOT_URLCONF = '%s.urls' % SITE_NAME
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME

# ---------- END DJANGO GENERAL CONFIGURATION


# ========== URL CONFIGURATION
#
Julien Furrer's avatar
Julien Furrer committed
118
119
def update_urls(base_url=None, name=__name__):
    this_module = modules[name]
120
121
    if base_url is None:
        base_url = getattr(this_module, 'BASE_URL', "/")
122
    setattr(this_module, 'BASE_URL', base_url)
123
124
    setattr(this_module, 'SESSION_COOKIE_PATH', base_url)
    setattr(this_module, 'CSRF_COOKIE_PATH', base_url)
125
126
127
    setattr(this_module, 'MEDIA_URL', '{}media/'.format(base_url))
    setattr(this_module, 'STATIC_URL', '{}static/'.format(base_url))
    setattr(this_module, 'CORS_URLS_REGEX', r'^{}api/.*$'.format(base_url))
128

Julien Furrer's avatar
Julien Furrer committed
129
update_urls("/")
130
131
132
133
134
135
136
137
138
139
140
141
142
# ---------- END URL CONFIGURATION


# ========== AUTHENTICATION
#
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

LOGIN_REDIRECT_URL = "adim.app:annotate-new"
LOGIN_URL = "adim.app:home"

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
143
144
SESSION_COOKIE_NAME = "adim_sessid"

145
146
147
148
149
# ---------- END AUTHENTICATION


# ========== LOCAL APPS CONFIGURATION
#
M. Chardon's avatar
M. Chardon committed
150
LOCAL_APPS = ('django_extensions','eav')
151
152
153
154
155
156

# ..... MISC
SENDFILE_BACKEND = 'sendfile.backends.xsendfile'


# ..... REST FRAMEWORK
157
LOCAL_APPS += ('rest_framework', 'rest_framework.authtoken')
158
159
160
161
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
162
        'adim_ttp.authentication.TTPAuthentication',
163
164
165
166
167
168
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ]
}

169
170
171
172
173
174
175
176
177
178

# ..... CORS HEADERS (https://github.com/ottoyiu/django-cors-headers/)
LOCAL_APPS += ('corsheaders',)
MIDDLEWARE_CLASSES = list(MIDDLEWARE_CLASSES)
MIDDLEWARE_CLASSES.insert(
    MIDDLEWARE_CLASSES.index('django.middleware.common.CommonMiddleware'),
    'corsheaders.middleware.CorsMiddleware'
)
MIDDLEWARE_CLASSES += ('corsheaders.middleware.CorsMiddleware', )
CORS_ORIGIN_ALLOW_ALL = True
179
# CORS_URLS_REGEX = r'^.*/api/.*$'
180
181


182
# ..... ADIM
183
LOCAL_APPS += ('adim', 'adim_app', 'adim_ttp')
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# Max file size in Mb
ADIM_UPLOAD_MAX_FILESIZE = 50

# Size of the Thumbnail
ADIM_THUMB_SIZE = (150, 150)

# When in PROD, DEBUG_JS if False and uses prod ready css too
ADIM_PROD = True

# If True load the non-minified version of adim js
ADIM_DEBUG_JS = False

# If the number of suggested adim-user is less than this value,
# the ldap will be queried too
ADIM_SUGGESTION = {
    'LIMIT': 7,
    'LDAP': {
        'URL': "ldap://ldap.unil.ch:389",
        'BASE': "o=universite de lausanne, c=ch",
        'TIMEOUT': 3
    }
}

207
208
209
210
211
212
ADIM_ENV = {
    'cimaf': {},
    'anodate': {
        'categories': {
            'default': [{
                'id': 'cat_1',
Julien Furrer's avatar
Julien Furrer committed
213
                'label': "Marqueur contextuel",
214
215
216
                'color': "#54848E"
            }, {
                'id': 'cat_3',
Julien Furrer's avatar
Julien Furrer committed
217
                'label': "Marqueur numérique",
218
                'color': "#6D557F"
Julien Furrer's avatar
Julien Furrer committed
219
220
221
222
            }, {
                'id': 'cat_7',
                'label': "Changement",
                'color': "#FF8B00"
223
224
            }, {
                'id': 'cat_4',
Julien Furrer's avatar
Julien Furrer committed
225
                'label': "Cycle",
226
227
228
                'color': "#D80918"
            }, {
                'id': 'cat_5',
Julien Furrer's avatar
Julien Furrer committed
229
                'label': "Chronologie",
230
231
                'color': "#71B800"
            }, {
Julien Furrer's avatar
Julien Furrer committed
232
233
234
235
236
237
238
239
240
241
242
                'id': 'cat_2',
                'label': "Sans catégorie",
                'color': "#D2D29F"
            # }, {
            #     'id': 'cat_6',
            #     'label': "Cycle",
            #     'color': "#EFC300"
            # }, {
            #     'id': 'cat_8',
            #     'label': "Contexte",
            #     'color': "#25BFD1"
243
            }]
M. Chardon's avatar
M. Chardon committed
244
        },
M. Chardon's avatar
M. Chardon committed
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
    },
    'geomo': {
        'categories': {
            'default': [{
                'id': 'cat_geo_1',
                'label': "Structural",
                'color': "#E1192E",
                'colorbg': "#ff7676"
            }, {
                'id': 'cat_geo_2',
                'label': "Hydrographie",
                'color': "#009CC4",
                'colorbg': "#87D2E7"
            }, {
                'id': 'cat_geo_3',
                'label': "Gravitaire",
                'color': "#DD9940",
                'colorbg': "#F0CA8F"
            }, {
                'id': 'cat_geo_4',
                'label': "Fluviatile",
                'color': "#00824B",
                'colorbg': "#58A57E"
            }, {
                'id': 'cat_geo_5',
                'label': "Glaciaire",
                'color': "#4B286A",
                'colorbg': "#A597B5"
            }, {
                'id': 'cat_geo_6',
                'label': "Périglaciaire",
                'color': "#BA106E",
                'colorbg': "#D988A9"
            }, {
                'id': 'cat_geo_7',
                'label': "Nival",
                'color': "#B01B21",
                'colorbg': "#C47D76"
            }, {
                'id': 'cat_geo_8',
                'label': "Karstique",
                'color': "#09A092",
                'colorbg': "#56BEB2"
            }, {
                'id': 'cat_geo_9',
                'label': "Organogène",
                'color': "#d1d17f",
                'colorbg': "#EBEBC7"
            }, {
                'id': 'cat_geo_10',
                'label': "Anthropique",
                'color': "#8A8B8A",
                'colorbg': "#BFC0BF"
            }, {
                'id': 'cat_geo_0',
                'label': "Sans catégorie",
                'color': "#c6c6c6",
                'colorbg': "#ededed"
            }]
        }
305
306
307
    }
}

308
309
310
311
312
313
314
315
316
AAI = {
    'SLO': True,
    # Not yet used
    'URLS': {
        'SP_LOGOUT': "https://jabba.unil.ch/Shibboleth.sso/Logout",
        'idp_LOGOUT': "https://aai.unil.ch/idp/logout.jsp"
    }
}

317
318
319
320
321
322
323
324
325
326
327
328
329

# ATTP = {
#     'OPTIONS': {
#         'CACHE_TIMEOUT': <the time in sec the ttp authorization result is kept in cache>
#     },
#     '<ttp_service_id>': {
#         'CHECK_URL' : <the url for authorization on the ttp>
#         'MODE_ID': <the sharing_mode value for that ttp. this should be a unique int > 15
#     }
# }
#
# CAUTION: when adding a ttp service, update the template (templates/adim/aom-modal.inc.html) with MODE_ID where needed
#
330
331
332
333
334
ATTP = {
    'OPTIONS': {
        'CACHE_TIMEOUT': 20,  # 30,
    },
    'moodle': {
335
        'CHECK_URL': "http://moodle2.unil.ch/mod/adim/checkAccess.php?uuid={uuid}",
336
        'MODE_ID': 16
337
338
    },
    'toto': {
339
340
        'CHECK_URL': "http://localhost/tests/phpupload/toto.php?a={uuid}",
        'MODE_ID': 24
341
342
    },
    'my_ttp': {
343
344
        'CHECK_URL': "http://my-ttp:8001/ttp/check/{uuid}/",
        'MODE_ID': 32
345
346
347
    }
}

Julien Furrer's avatar
Julien Furrer committed
348
349
350
351
352
353
354
355
356
357

# ..... SHIBAUTH
LOCAL_APPS += ('shibauth', )
AUTHENTICATION_BACKENDS = ('shibauth.shibbolethbackends.ShibbolethBackend',) + AUTHENTICATION_BACKENDS

try:
    from .components.shibbauth import *
except ImportError:
    raise ImproperlyConfigured("Unable to import SHIBAUTH configurations")

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# ---------- END LOCAL APPS CONFIGURATION


# ========== APPS CONFIGURATION
#
DJANGO_APPS = (
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)
INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS
# ---------- END APPS CONFIGURATION

M. Chardon's avatar
M. Chardon committed
375
SERVER_EMAIL = 'marion.chardon@unil.ch'
376
377
EMAIL_HOST = "smtp.unil.ch"

378

379
380
381
# ========== LOGGING CONFIGURATION
#
def add_remote_info(record):
382
383
384
385
386
387
388
    """
    Pour utiliser, utilisez le logger comme:
        logger.debug("Coucou", extra={'request': request})

    :param record:
    :return:
    """
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    req = getattr(record, 'request', None)
    record.remote_addr = req.META.get('REMOTE_ADDR', '-') if req else '-'
    record.forwarded_for = req.META.get('HTTP_X_FORWARDED_FOR', '-') if req else '-'
    return True


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue'
        },
        'add_remote_info': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': add_remote_info,
408
409
410
411
        },
        'save_emails_to_disk': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': lambda x: False,
412
        }
413

414
415
416
    },
    'formatters': {
        'verbose': {
417
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)d %(message)s',
418
419
        },
        'verbose_with_remote': {
420
            'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)d %(remote_addr)s %(forwarded_for)s %(message)s',
421
422
423
424
425
426
427
428
429
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
430
            'include_html': False,
431
432
            'class': 'django.utils.log.AdminEmailHandler'
        },
433
434
435
436
437
438
439
        'mail_admins_file': {
            'level': 'ERROR',
            'filters': ['require_debug_false', 'save_emails_to_disk'],
            'include_html': False,
            'class': 'django.utils.log.AdminEmailHandler',
            'email_backend': 'django.core.mail.backends.filebased.EmailBackend'
        },
440
441
442
443
        'console': {
            'filters': ['require_debug_true', ],
            'class': 'logging.StreamHandler',
        },
444
        'file_debug': {
Julien Furrer's avatar
Julien Furrer committed
445
            'level': 'DEBUG',
446
447
            # 'class': 'logging.FileHandler',
            'class': 'logging.handlers.WatchedFileHandler',
448
449
450
451
            'filters': ['add_remote_info', ],
            'formatter': 'verbose_with_remote',
            'filename': '{}/log/debug.log'.format(dirname(SITE_ROOT)),
        },
Julien Furrer's avatar
Julien Furrer committed
452
453
454
455
456
457
458
459
        'file': {
            'level': 'INFO',
            # 'class': 'logging.FileHandler',
            'class': 'logging.handlers.WatchedFileHandler',
            'filters': ['add_remote_info', ],
            'formatter': 'verbose',
            'filename': '{}/log/error.log'.format(dirname(SITE_ROOT)),
        },
460
461
462
    },
    'loggers': {
        'django.request': {
Julien Furrer's avatar
Julien Furrer committed
463
            'handlers': ['mail_admins', 'mail_admins_file', 'file_debug', 'file' ],
464
465
466
            'level': 'WARNING',
            'propagate': True,
        },
467
468
469
470
471
        'adim.permissions': {
            'handlers': ['console'],
            'level': 'DEBUG',  # 'NOTSET',
            'propagate': True,
        },
472
        'adim_app': {
Julien Furrer's avatar
Julien Furrer committed
473
            'handlers': ['console', 'file_debug', 'file'],
474
475
476
477
            'level': 'DEBUG',
            'propagate': True,
        },
        'adim_ttp': {
Julien Furrer's avatar
Julien Furrer committed
478
            'handlers': ['console', 'file_debug', 'file'],
479
480
481
            'level': 'DEBUG',
            'propagate': True,
        },
482
        'shibauth': {
Julien Furrer's avatar
Julien Furrer committed
483
            'handlers': ['console', 'file_debug', 'file'],
484
485
486
            'level': 'DEBUG',
            'propagate': True,
        },
487
488
    }
}
489
########## END LOGGING CONFIGURATION