· 6 years ago · Jun 11, 2019, 06:38 PM
1# -*- coding: utf-8 -*-
2#import ldap
3import os, json
4
5from django.utils.translation import ugettext_lazy as _
6
7#from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
8# a massive hack to see if we're testing, in which case we use different settings
9import sys
10TESTING = 'test' in sys.argv
11
12# go through environment variables and override them
13def get_from_env(var, default):
14 if not TESTING and os.environ.has_key(var):
15 return os.environ[var]
16 else:
17 return default
18
19DEBUG = (get_from_env('DEBUG', '1') == '1')
20TEMPLATE_DEBUG = DEBUG
21
22#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.
23#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.
24#This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.
25#More info: https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts
26
27# set a value for production environment, alongside with debug set to false
28ALLOWED_HOSTS = ['vote.domain.com']
29
30# Make this unique, and don't share it with anybody.
31SECRET_KEY = get_from_env('SECRET_KEY', 'secret')
32ROOT_URLCONF = 'urls'
33
34ROOT_PATH = os.path.dirname(__file__)
35
36# add admins of the form:
37# ('Ben Adida', 'ben@adida.net'),
38# if you want to be emailed about errors.
39ADMINS = (
40)
41
42MANAGERS = ADMINS
43
44# is this the master Helios web site?
45MASTER_HELIOS = (get_from_env('MASTER_HELIOS', '0') == '1')
46
47# show ability to log in? (for example, if the site is mostly used by voters)
48# if turned off, the admin will need to know to go to /auth/login manually
49SHOW_LOGIN_OPTIONS = (get_from_env('SHOW_LOGIN_OPTIONS', '1') == '1')
50
51# sometimes, when the site is not that social, it's not helpful
52# to display who created the election
53SHOW_USER_INFO = (get_from_env('SHOW_USER_INFO', '1') == '1')
54
55DATABASES = {
56 'default': {
57 'ENGINE': 'django.db.backends.postgresql_psycopg2',
58 'NAME': 'helios'
59 }
60}
61
62SOUTH_DATABASE_ADAPTERS = {'default':'south.db.postgresql_psycopg2'}
63
64# override if we have an env variable
65if get_from_env('DATABASE_URL', None):
66 import dj_database_url
67 DATABASES['default'] = dj_database_url.config()
68 DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
69 DATABASES['default']['CONN_MAX_AGE'] = 600
70
71 # require SSL
72 DATABASES['default']['OPTIONS'] = {'sslmode': 'require'}
73
74# Local time zone for this installation. Choices can be found here:
75# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
76# although not all choices may be available on all operating systems.
77# If running in a Windows environment this must be set to the same as your
78# system time zone.
79TIME_ZONE = 'America/Cuiaba'
80LANGUAGE_CODE = 'pt-br'
81SITE_ID = 1
82USE_I18N = True
83USE_TZ = True
84
85LANGUAGES = (
86 ('en', _('English')),
87 ('pt-br', _('Brazilian Portuguese')),
88)
89
90LOCALE_PATHS = (
91 ROOT_PATH + '/locale',
92)
93
94
95# Absolute path to the directory that holds media.
96# Example: "/home/media/media.lawrence.com/"
97MEDIA_ROOT = '/srv/helios-server/server_ui/media'
98
99# URL that handles the media served from MEDIA_ROOT. Make sure to use a
100# trailing slash if there is a path component (optional in other cases).
101# Examples: "http://media.lawrence.com", "http://example.com/media/"
102MEDIA_URL = ''
103
104# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
105# trailing slash.
106# Examples: "http://foo.com/media/", "/media/".
107STATIC_URL = '/admin-media/'
108
109STATIC_ROOT = ROOT_PATH + '/sitestatic'
110
111STATICFILES_DIRS = (
112 ROOT_PATH + '/heliosbooth',
113 ROOT_PATH + '/heliosverifier',
114 ROOT_PATH + '/helios_auth/media',
115 ROOT_PATH + '/helios/media',
116 ROOT_PATH + '/server_ui/media',
117 ROOT_PATH + '/heliosinstitution/media/',
118)
119
120
121# 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."
122# If in production, you got a bad request (400) error
123#More info: https://docs.djangoproject.com/en/1.7/ref/settings/#allowed-hosts (same for 1.6)
124
125
126# Secure Stuff
127if (get_from_env('SSL', '0') == '1'):
128 SECURE_SSL_REDIRECT = True
129 SESSION_COOKIE_SECURE = True
130
131 # tuned for Heroku
132 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
133
134SESSION_COOKIE_HTTPONLY = True
135
136# let's go with one year because that's the way to do it now
137STS = False
138if (get_from_env('HSTS', '0') == '1'):
139 STS = True
140 # we're using our own custom middleware now
141 # SECURE_HSTS_SECONDS = 31536000
142 # not doing subdomains for now cause that is not likely to be necessary and can screw things up.
143 # SECURE_HSTS_INCLUDE_SUBDOMAINS = True
144
145SECURE_BROWSER_XSS_FILTER = True
146SECURE_CONTENT_TYPE_NOSNIFF = True
147
148# List of callables that know how to import templates from various sources.
149TEMPLATE_LOADERS = (
150 'django.template.loaders.filesystem.Loader',
151 'django.template.loaders.app_directories.Loader'
152)
153
154MIDDLEWARE_CLASSES = (
155 # make all things SSL
156 #'sslify.middleware.SSLifyMiddleware',
157
158 # secure a bunch of things
159 'djangosecure.middleware.SecurityMiddleware',
160 'helios.security.HSTSMiddleware',
161 'django.middleware.clickjacking.XFrameOptionsMiddleware',
162
163 'django.middleware.common.CommonMiddleware',
164 'django.contrib.sessions.middleware.SessionMiddleware',
165 'django.contrib.auth.middleware.AuthenticationMiddleware',
166 'django.contrib.messages.middleware.MessageMiddleware'
167
168 # 'flatpages_i18n.middleware.FlatpageFallbackMiddleware'
169)
170
171
172TEMPLATE_DIRS = (
173 ROOT_PATH,
174 os.path.join(ROOT_PATH, 'templates')
175)
176
177INSTALLED_APPS = (
178 'django.contrib.auth',
179 'django.contrib.contenttypes',
180 'djangosecure',
181 'django.contrib.sessions',
182 'django.contrib.sites',
183 'django.contrib.staticfiles',
184 'django.contrib.messages',
185 'django.contrib.admin',
186 ## needed for queues
187 'djcelery',
188 'kombu.transport.django',
189 ## in Django 1.7 we now use built-in migrations, no more south
190 ## 'south',
191 ## HELIOS stuff
192 'helios_auth',
193 'helios',
194 'server_ui',
195 'helioslog',
196 'heliosinstitution',
197)
198
199##
200## HELIOS
201##
202
203
204MEDIA_ROOT = ROOT_PATH + "media/"
205
206# a relative path where voter upload files are stored
207VOTER_UPLOAD_REL_PATH = "voters/%Y/%m/%d"
208
209
210# Change your email settings
211EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
212#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
213EMAIL_USE_TLS = False
214EMAIL_HOST = 'localhost'
215EMAIL_PORT = 25
216EMAIL_HOST_USER = ''
217EMAIL_HOST_PASSWORD = ''
218DEFAULT_FROM_EMAIL = get_from_env('DEFAULT_FROM_EMAIL', 'username@gmail.com')
219DEFAULT_FROM_NAME = get_from_env('DEFAULT_FROM_NAME', 'Votação Eletrônica')
220SERVER_EMAIL = '%s <%s>' % (DEFAULT_FROM_NAME, DEFAULT_FROM_EMAIL)
221
222LOGIN_URL = '/auth/'
223LOGOUT_ON_CONFIRMATION = True
224
225# The two hosts are here so the main site can be over plain HTTP
226# while the voting URLs are served over SSL.
227URL_HOST = get_from_env("URL_HOST", "http://vote.domain.com").rstrip("/")
228
229# IMPORTANT: you should not change this setting once you've created
230# elections, as your elections' cast_url will then be incorrect.
231# SECURE_URL_HOST = "https://localhost:8443"
232SECURE_URL_HOST = get_from_env("SECURE_URL_HOST", URL_HOST).rstrip("/")
233
234# election stuff
235SITE_TITLE = get_from_env('SITE_TITLE', _('E-Voting System'))
236MAIN_LOGO_URL = get_from_env('MAIN_LOGO_URL', '/static/logo.png')
237ALLOW_ELECTION_INFO_URL = (get_from_env('ALLOW_ELECTION_INFO_URL', '0') == '1')
238
239# FOOTER links
240FOOTER_LINKS = json.loads(get_from_env('FOOTER_LINKS', '[]'))
241FOOTER_LOGO_URL = get_from_env('FOOTER_LOGO_URL', None)
242
243WELCOME_MESSAGE = get_from_env('WELCOME_MESSAGE', _('Welcome to E-Voting System.'))
244
245HELP_EMAIL_ADDRESS = get_from_env('HELP_EMAIL_ADDRESS', 'ti@domain.com')
246
247AUTH_TEMPLATE_BASE = "server_ui/templates/base.html"
248HELIOS_TEMPLATE_BASE = "server_ui/templates/base.html"
249AUTH_TEMPLATE_BASENONAV = "server_ui/templates/basenonav.html"
250HELIOS_TEMPLATE_BASENONAV = "server_ui/templates/basenonav.html"
251HELIOS_ADMIN_ONLY = False
252HELIOS_VOTERS_UPLOAD = True
253HELIOS_VOTERS_EMAIL = True
254
255# are elections private by default?
256HELIOS_PRIVATE_DEFAULT = True
257
258# authentication systems enabled
259AUTH_ENABLED_AUTH_SYSTEMS = ['password']
260#AUTH_ENABLED_AUTH_SYSTEMS = get_from_env('AUTH_ENABLED_AUTH_SYSTEMS', 'shibboleth').split(",")
261#AUTH_DEFAULT_AUTH_SYSTEM = get_from_env('AUTH_DEFAULT_AUTH_SYSTEM', 'shibboleth')
262#AUTH_ENABLED_AUTH_SYSTEMS = get_from_env('AUTH_ENABLED_AUTH_SYSTEMS', 'ldap').split(",")
263AUTH_DEFAULT_AUTH_SYSTEM = get_from_env('AUTH_DEFAULT_AUTH_SYSTEM', 'password')
264
265# google
266GOOGLE_CLIENT_ID = get_from_env('GOOGLE_CLIENT_ID', '')
267GOOGLE_CLIENT_SECRET = get_from_env('GOOGLE_CLIENT_SECRET', '')
268
269# facebook
270FACEBOOK_APP_ID = get_from_env('FACEBOOK_APP_ID','')
271FACEBOOK_API_KEY = get_from_env('FACEBOOK_API_KEY','')
272FACEBOOK_API_SECRET = get_from_env('FACEBOOK_API_SECRET','')
273
274# twitter
275TWITTER_API_KEY = ''
276TWITTER_API_SECRET = ''
277TWITTER_USER_TO_FOLLOW = 'heliosvoting'
278TWITTER_REASON_TO_FOLLOW = "we can direct-message you when the result has been computed in an election in which you participated"
279
280# the token for Helios to do direct messaging
281TWITTER_DM_TOKEN = {"oauth_token": "", "oauth_token_secret": "", "user_id": "", "screen_name": ""}
282
283# LinkedIn
284LINKEDIN_API_KEY = ''
285LINKEDIN_API_SECRET = ''
286
287# CAS (for universities)
288CAS_USERNAME = get_from_env('CAS_USERNAME', "")
289CAS_PASSWORD = get_from_env('CAS_PASSWORD', "")
290CAS_ELIGIBILITY_URL = get_from_env('CAS_ELIGIBILITY_URL', "")
291CAS_ELIGIBILITY_REALM = get_from_env('CAS_ELIGIBILITY_REALM', "")
292
293# Clever
294CLEVER_CLIENT_ID = get_from_env('CLEVER_CLIENT_ID', "")
295CLEVER_CLIENT_SECRET = get_from_env('CLEVER_CLIENT_SECRET', "")
296
297# to use AWS Simple Email Service
298# in which case environment should contain
299# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
300if get_from_env('EMAIL_USE_AWS', '0') == '1':
301 EMAIL_BACKEND = 'django_ses.SESBackend'
302
303# set up logging
304import logging
305logging.basicConfig(
306 level = logging.DEBUG,
307 format = '%(asctime)s %(levelname)s %(message)s'
308)
309
310
311# set up django-celery
312# BROKER_BACKEND = "kombu.transport.DatabaseTransport"
313BROKER_URL = "django://"
314CELERY_RESULT_DBURI = DATABASES['default']
315import djcelery
316djcelery.setup_loader()
317
318CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
319
320CELERY_TASK_RESULT_EXPIRES = 5184000 # 60 days
321# for testing
322TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'
323# this effectively does CELERY_ALWAYS_EAGER = True
324
325# see configuration example at https://pythonhosted.org/django-auth-ldap/example.html
326#AUTH_LDAP_SERVER_URI = "ldap://ldap.forumsys.com" # replace by your Ldap URI
327#AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com"
328#AUTH_LDAP_BIND_PASSWORD = "password"
329#AUTH_LDAP_USER_SEARCH = LDAPSearch("dc=example,dc=com",
330# ldap.SCOPE_SUBTREE, "(uid=%(user)s)"
331#)
332
333#AUTH_LDAP_USER_ATTR_MAP = {
334# "first_name": "givenName",
335# "last_name": "sn",
336# "email": "mail",
337#}
338
339#AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True
340
341#AUTH_LDAP_ALWAYS_UPDATE_USER = False
342
343AUTH_BIND_USERID_TO_VOTERID = ['password']
344
345# Shibboleth auth settings
346SHIBBOLETH_ATTRIBUTE_MAP = {
347 #"Shibboleth-givenName": (True, "first_name"),
348 "Shib-inetOrgPerson-cn": (True, "common_name"),
349 "Shib-inetOrgPerson-sn": (True, "last_name"),
350 "Shib-inetOrgPerson-mail": (True, "email"),
351 "Shib-eduPerson-eduPersonPrincipalName": (True, "eppn"),
352 "Shib-brEduPerson-brEduAffiliationType": (True, "affiliation"),
353 "Shib-Identity-Provider": (True, "identity_provider"),
354}
355
356FEDERATION_NAME = "CAFe Expresso"
357
358# To use some manager-specific attributes, like idp address
359USE_ELECTION_MANAGER_ATTRIBUTES = True
360
361ELECTION_MANAGER_ATTRIBUTES = ['Provider']
362
363INSTITUTION_ROLE = ['Institution Admin','Election Admin']
364
365ATTRIBUTES_AUTOMATICALLY_CHECKED = ['brExitDate']
366
367SESSION_EXPIRE_AT_BROWSER_CLOSE = True
368
369USE_EMBEDDED_DS = False
370# end shibboleth auth settings
371# Rollbar Error Logging
372ROLLBAR_ACCESS_TOKEN = get_from_env('ROLLBAR_ACCESS_TOKEN', None)
373if ROLLBAR_ACCESS_TOKEN:
374 print "setting up rollbar"
375 MIDDLEWARE_CLASSES += ('rollbar.contrib.django.middleware.RollbarNotifierMiddleware',)
376 ROLLBAR = {
377 'access_token': ROLLBAR_ACCESS_TOKEN,
378 'environment': 'development' if DEBUG else 'production',
379 }
380
381FEATURE_ELECTION = True
382
383LOGGING = {
384 'version': 1,
385 'disable_existing_loggers': False,
386 'handlers': {
387 'null': {
388 'class': 'logging.NullHandler',
389 }
390 },
391 'loggers': {
392 'django.security.DisallowedHost': {
393 'handlers' : ['null'],
394 'propagate': False,
395 }
396 }
397}