Repository navigation
Expand file tree
/
Copy pathsettings.py
More file actions
483 lines (385 loc) · 16.2 KB
/
Copy pathsettings.py
File metadata and controls
483 lines (385 loc) · 16.2 KB
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
# -*- coding: utf-8 -*-
import json
import os
import sys
import ldap
from django.utils.translation import gettext_lazy as _
from django_auth_ldap.config import LDAPSearch
# a massive hack to see if we're testing, in which case we use different settings
TESTING = 'test' in sys.argv
# go through environment variables and override them
def get_from_env(var, default):
if not TESTING and var in os.environ:
return os.environ[var]
else:
return default
DEBUG = (get_from_env('DEBUG', '1') == '1')
#If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation.
#When DEBUG is True or when running tests, host validation is disabled; any host will be accepted. Thus it’s usually only necessary to set it in production.
#This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.
#More info: https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts
# set a value for production environment, alongside with debug set to false
ALLOWED_HOSTS = get_from_env('ALLOWED_HOSTS', 'localhost').split(",")
# Make this unique, and don't share it with anybody.
SECRET_KEY = get_from_env('SECRET_KEY', 'replaceme')
ROOT_URLCONF = 'urls'
ROOT_PATH = os.path.dirname(__file__)
# add admins of the form:
# ('Ben Adida', 'ben@adida.net'),
# if you want to be emailed about errors.
admin_email = get_from_env('ADMIN_EMAIL', None)
if admin_email:
ADMINS = [(get_from_env('ADMIN_NAME', ''), admin_email)]
else:
ADMINS = []
MANAGERS = ADMINS
# is this the master Helios web site?
MASTER_HELIOS = (get_from_env('MASTER_HELIOS', '0') == '1')
# show ability to log in? (for example, if the site is mostly used by voters)
# if turned off, the admin will need to know to go to /auth/login manually
SHOW_LOGIN_OPTIONS = (get_from_env('SHOW_LOGIN_OPTIONS', '1') == '1')
# sometimes, when the site is not that social, it's not helpful
# to display who created the election
SHOW_USER_INFO = (get_from_env('SHOW_USER_INFO', '1') == '1')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': get_from_env('DB_NAME', 'helios'),
'USER': get_from_env('DB_USER', 'helios'),
'PASSWORD': get_from_env('DB_PWD', 'helios'),
'HOST': get_from_env('POSTGRES_HOST', 'db'),
'PORT': get_from_env('POSTGRES_PORT', '5432'),
'CONN_MAX_AGE': 600,
}
}
# override if we have an env variable
if get_from_env('DATABASE_URL', None):
import dj_database_url
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql'
# explicitly set the default auto-created primary field to silence warning models.W042
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
# 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.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Sao_Paulo'
LANGUAGE_CODE = 'pt-br'
SITE_ID = 1
USE_I18N = True
USE_TZ = True
LANGUAGES = (
('en', _('English')),
('pt-br', _('Brazilian Portuguese')),
)
LOCALE_PATHS = (
ROOT_PATH + '/locale',
)
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# 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 = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
STATIC_URL = '/media/'
STATIC_ROOT = ROOT_PATH + '/staticfiles'
STATICFILES_DIRS = (
ROOT_PATH + '/heliosbooth',
ROOT_PATH + '/heliosverifier',
ROOT_PATH + '/helios_auth/media',
ROOT_PATH + '/helios/media',
ROOT_PATH + '/server_ui/media',
ROOT_PATH + '/heliosinstitution/media/',
)
# Secret key for HMAC confirmation codes (separate from Django SECRET_KEY)
EMAIL_OPTOUT_SECRET = get_from_env('EMAIL_OPTOUT_SECRET', 'replace-with-secure-random-key')
# If debug is set to false and ALLOWED_HOSTS is not declared, django raises "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False."
# If in production, you got a bad request (400) error
#More info: https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts (same for 1.6)
# Secure Stuff
if get_from_env('SSL', '0') == '1':
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
# tuned for Heroku
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SESSION_COOKIE_HTTPONLY = True
# Set this explicitly rather than relying on the Django default: it is a load-bearing
# part of our CSRF defense, since Helios does its own CSRF checking (check_csrf) rather
# than using Django's CsrfViewMiddleware. 'Lax' keeps the session cookie off every
# cross-site POST and off cross-site GET subresources (images, iframes, fetch), while
# still allowing ordinary inbound links to Helios to stay logged in.
SESSION_COOKIE_SAMESITE = get_from_env('SESSION_COOKIE_SAMESITE', 'Lax')
# let's go with one year because that's the way to do it now
STS = False
if get_from_env('HSTS', '0') == '1':
STS = True
# we're using our own custom middleware now
# SECURE_HSTS_SECONDS = 31536000
# not doing subdomains for now cause that is not likely to be necessary and can screw things up.
# SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
# Content Security Policy Configuration (django-csp)
# https://django-csp.readthedocs.io/
#
# 'unsafe-inline' and 'unsafe-eval' are required due to legacy inline scripts,
# onclick handlers, and jQuery JSON eval usage. Future improvement: use nonces.
CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'")
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'")
CSP_IMG_SRC = ("'self'", "data:")
CSP_FONT_SRC = ("'self'",)
CSP_CONNECT_SRC = ("'self'",)
CSP_WORKER_SRC = ("'self'", "blob:")
CSP_FORM_ACTION = ("'self'",)
CSP_FRAME_ANCESTORS = ("'self'",)
CSP_BASE_URI = ("'self'",)
CSP_OBJECT_SRC = ("'none'",)
# Set CSP_REPORT_ONLY=1 to test without enforcing
if get_from_env('CSP_REPORT_ONLY', '0') == '1':
CSP_REPORT_ONLY = True
else:
CSP_REPORT_ONLY = False
# Optional: URI to receive CSP violation reports
_csp_report_uri = get_from_env('CSP_REPORT_URI', None)
if _csp_report_uri:
CSP_REPORT_URI = _csp_report_uri
SILENCED_SYSTEM_CHECKS = ['urls.W002']
MIDDLEWARE = [
# secure a bunch of things
'django.middleware.security.SecurityMiddleware',
'helios.security.HSTSMiddleware',
'csp.middleware.CSPMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# 'flatpages_i18n.middleware.FlatpageFallbackMiddleware'
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
ROOT_PATH,
os.path.join(ROOT_PATH, 'templates'),
# os.path.join(ROOT_PATH, 'helios/templates'), # covered by APP_DIRS:True
# os.path.join(ROOT_PATH, 'helios_auth/templates'), # covered by APP_DIRS:True
# os.path.join(ROOT_PATH, 'server_ui/templates'), # covered by APP_DIRS:True
],
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
}
},
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.staticfiles',
'django.contrib.messages',
'django.contrib.admin',
'anymail',
## HELIOS stuff
'helios_auth',
'helios',
'server_ui',
'helioslog',
'heliosinstitution',
'django_celery_results',
'django_celery_beat'
)
# Email backend configuration
# In development mode, set EMAIL_USE_CONSOLE=1 to print emails to stdout
if DEBUG and get_from_env('EMAIL_USE_CONSOLE', '0') == '1':
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ANYMAIL = {
"MAILGUN_API_KEY": get_from_env('MAILGUN_API_KEY', None),
}
# Mailgun overrides console backend if configured
if ANYMAIL["MAILGUN_API_KEY"]:
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
##
## HELIOS
##
MEDIA_ROOT = ROOT_PATH + "media/"
# a relative path where voter upload files are stored
VOTER_UPLOAD_REL_PATH = "voters/%Y/%m/%d"
# Change your email settings
DEFAULT_FROM_EMAIL = get_from_env('DEFAULT_FROM_EMAIL', 'heliosvoting.pt@gmail.com')
DEFAULT_FROM_NAME = get_from_env('DEFAULT_FROM_NAME', 'Sistema de Votação Eletrônica')
SERVER_EMAIL = '%s <%s>' % (DEFAULT_FROM_NAME, DEFAULT_FROM_EMAIL)
LOGIN_URL = '/auth/'
LOGOUT_ON_CONFIRMATION = True
# The two hosts are here so the main site can be over plain HTTP
# while the voting URLs are served over SSL.
URL_HOST = get_from_env("URL_HOST", "http://localhost").rstrip("/")
# IMPORTANT: you should not change this setting once you've created
# elections, as your elections' cast_url will then be incorrect.
# SECURE_URL_HOST = "https://localhost:8443"
SECURE_URL_HOST = get_from_env("SECURE_URL_HOST", URL_HOST).rstrip("/")
# election stuff
SITE_TITLE = get_from_env('SITE_TITLE', _('IFSC E-Voting System'))
MAIN_LOGO_URL = get_from_env('MAIN_LOGO_URL', '/static/logo.png')
ALLOW_ELECTION_INFO_URL = (get_from_env('ALLOW_ELECTION_INFO_URL', '0') == '1')
# FOOTER links
FOOTER_LINKS = json.loads(get_from_env('FOOTER_LINKS', '[]'))
FOOTER_LOGO_URL = get_from_env('FOOTER_LOGO_URL', None)
WELCOME_MESSAGE = get_from_env('WELCOME_MESSAGE', _('Welcome to IFSC E-Voting System'))
HELP_EMAIL_ADDRESS = get_from_env('HELP_EMAIL_ADDRESS', 'shirlei@gmail.com')
AUTH_TEMPLATE_BASE = "server_ui/templates/base.html"
HELIOS_TEMPLATE_BASE = "server_ui/templates/base.html"
AUTH_TEMPLATE_BASENONAV = "server_ui/templates/basenonav.html"
HELIOS_TEMPLATE_BASENONAV = "server_ui/templates/basenonav.html"
HELIOS_ADMIN_ONLY = True
HELIOS_VOTERS_UPLOAD = True
HELIOS_VOTERS_EMAIL = True
# Number of weeks after tallying when voter emails should be disabled
HELIOS_VOTER_EMAIL_CUTOFF_WEEKS = int(get_from_env('HELIOS_VOTER_EMAIL_CUTOFF_WEEKS', '3'))
# are elections private by default?
HELIOS_PRIVATE_DEFAULT = True
# authentication systems enabled
# AUTH_ENABLED_SYSTEMS = ['password','facebook', 'google', 'yahoo']
AUTH_ENABLED_SYSTEMS = get_from_env('AUTH_ENABLED_SYSTEMS',
get_from_env('AUTH_ENABLED_AUTH_SYSTEMS', 'ldap,password,google,facebook,discourse')
).split(",")
# Add development login in debug mode
if DEBUG:
AUTH_ENABLED_SYSTEMS = ['devlogin'] + AUTH_ENABLED_SYSTEMS
AUTH_DEFAULT_SYSTEM = get_from_env('AUTH_DEFAULT_SYSTEM', get_from_env('AUTH_DEFAULT_AUTH_SYSTEM', None))
# google
GOOGLE_CLIENT_ID = get_from_env('GOOGLE_CLIENT_ID', '')
GOOGLE_CLIENT_SECRET = get_from_env('GOOGLE_CLIENT_SECRET', '')
# facebook
FACEBOOK_APP_ID = get_from_env('FACEBOOK_APP_ID','')
FACEBOOK_API_KEY = get_from_env('FACEBOOK_API_KEY','')
FACEBOOK_API_SECRET = get_from_env('FACEBOOK_API_SECRET','')
# LinkedIn
LINKEDIN_CLIENT_ID = get_from_env('LINKEDIN_CLIENT_ID', '')
LINKEDIN_CLIENT_SECRET = get_from_env('LINKEDIN_CLIENT_SECRET', '')
# CAS (for universities)
CAS_USERNAME = get_from_env('CAS_USERNAME', "")
CAS_PASSWORD = get_from_env('CAS_PASSWORD', "")
CAS_ELIGIBILITY_URL = get_from_env('CAS_ELIGIBILITY_URL', "")
CAS_ELIGIBILITY_REALM = get_from_env('CAS_ELIGIBILITY_REALM', "")
# GitHub
GH_CLIENT_ID = get_from_env('GH_CLIENT_ID', '')
GH_CLIENT_SECRET = get_from_env('GH_CLIENT_SECRET', '')
# Gitlab
GITLAB_CLIENT_ID = get_from_env('GITLAB_CLIENT_ID', "")
GITLAB_CLIENT_SECRET = get_from_env('GITLAB_CLIENT_SECRET', "")
# Discourse (Discourse Connect provider: shared-secret HMAC, no client id/secret)
DISCOURSE_URL = get_from_env('DISCOURSE_URL', '')
DISCOURSE_SECRET = get_from_env('DISCOURSE_SECRET', '')
# email server
EMAIL_HOST = get_from_env('EMAIL_HOST', 'localhost')
EMAIL_PORT = int(get_from_env('EMAIL_PORT', "2525"))
EMAIL_HOST_USER = get_from_env('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = get_from_env('EMAIL_HOST_PASSWORD', '')
EMAIL_USE_TLS = (get_from_env('EMAIL_USE_TLS', '0') == '1')
# to use AWS Simple Email Service
# in which case environment should contain
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
if get_from_env('EMAIL_USE_AWS', '0') == '1':
EMAIL_BACKEND = 'django_ses.SESBackend'
# set up logging
import logging
logging.basicConfig(
level=logging.DEBUG if TESTING else logging.INFO,
format='%(asctime)s %(levelname)s %(message)s'
)
# set up celery
if TESTING:
CELERY_TASK_ALWAYS_EAGER = True
else:
CELERY_TASK_ALWAYS_EAGER = (get_from_env('CELERY_TASK_ALWAYS_EAGER', '0') == '1')
CELERY_BROKER_URL = get_from_env('CELERY_BROKER_URL', 'redis://127.0.0.1:6379')
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = 'django-db'
CELERY_CACHE_BACKEND = 'django-cache'
CELERY_RESULT_EXPIRES = 5184000 # 60 dias
# see configuration example at https://pythonhosted.org/django-auth-ldap/example.html
AUTH_LDAP_SERVER_URI = get_from_env('LDAP_SERVER_URI', '') # replace by your Ldap URI
AUTH_LDAP_BIND_DN = get_from_env('LDAP_BIND_DN','')
AUTH_LDAP_BIND_PASSWORD = get_from_env('LDAP_BIND_PASSWORD', '')
AUTH_LDAP_USER_SEARCH = LDAPSearch(get_from_env('LDAP_USER_SEARCH',''),
ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
)
# Test LDAP
# AUTH_LDAP_SERVER_URI = "ldap://ldap.forumsys.com" # replace by your Ldap URI
# AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com"
# AUTH_LDAP_BIND_PASSWORD = "password"
# AUTH_LDAP_USER_SEARCH = LDAPSearch("dc=example,dc=com",
# ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
# )
AUTH_LDAP_USER_ATTR_MAP = {
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}
AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True
AUTH_LDAP_ALWAYS_UPDATE_USER = False
AUTH_BIND_USERID_TO_VOTERID = ['ldap']
# Shibboleth auth settings
SHIBBOLETH_ATTRIBUTE_MAP = {
#"Shibboleth-givenName": (True, "first_name"),
"Shib-inetOrgPerson-cn": (True, "common_name"),
"Shib-inetOrgPerson-sn": (True, "last_name"),
"Shib-inetOrgPerson-mail": (True, "email"),
"Shib-eduPerson-eduPersonPrincipalName": (True, "eppn"),
"Shib-brEduPerson-brEduAffiliationType": (True, "affiliation"),
"Shib-Identity-Provider": (True, "identity_provider"),
}
FEDERATION_NAME = "CAFe Expresso"
# To use some manager-specific attributes, like idp address
USE_ELECTION_MANAGER_ATTRIBUTES = True
ELECTION_MANAGER_ATTRIBUTES = ['Provider']
INSTITUTION_ROLE = ['Institution Admin','Election Admin']
ATTRIBUTES_AUTOMATICALLY_CHECKED = ['brExitDate']
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
USE_EMBEDDED_DS = False
# end shibboleth auth settings
# Rollbar Error Logging
ROLLBAR_ACCESS_TOKEN = get_from_env('ROLLBAR_ACCESS_TOKEN', None)
if ROLLBAR_ACCESS_TOKEN:
print("setting up rollbar")
MIDDLEWARE += ['rollbar.contrib.django.middleware.RollbarNotifierMiddleware',]
ROLLBAR = {
'access_token': ROLLBAR_ACCESS_TOKEN,
'environment': 'development' if DEBUG else 'production',
}
FEATURE_ELECTION = False
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'null': {
'class': 'logging.NullHandler',
}
},
'loggers': {
'django.security.DisallowedHost': {
'handlers' : ['null'],
'propagate': False,
}
}
}
# Default voter type, to allow uploading a voter file without
# informing voter type
# must be one type valid in AUTH_SYSTEMS (helios_auth/auth_systems/__init__.py)
DEFAULT_VOTER_TYPE = 'password'
SHOW_VOTER_UPLOAD_MISC = True