base.py 12.6 KB
Newer Older
1
"""Common settings and globals."""
Őry Máté committed
2
# flake8: noqa
3
from os import environ
4 5 6 7
from os.path import abspath, basename, dirname, join, normpath, isfile
from sys import path

from django.core.exceptions import ImproperlyConfigured
8
from django.utils.translation import ugettext_lazy as _
9
from json import loads
10 11


Kálmán Viktor committed
12
# from socket import SOCK_STREAM
13

14

15 16 17
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.

Kálmán Viktor committed
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
def get_env_variable(var_name, default=None):
    """ Get the environment variable or return exception/default """
    try:
        return environ[var_name]
    except KeyError:
        if default is None:
            error_msg = "Set the %s environment variable" % var_name
            raise ImproperlyConfigured(error_msg)
        else:
            return default


########## 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)

41
# Url to site: (e.g. http://localhost:8080/)
42
DJANGO_URL = get_env_variable('DJANGO_URL', '/')
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
# 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


########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = False

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION


########## MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (
    ('Root', 'root@localhost'),
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
########## END MANAGER CONFIGURATION


########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.' +
Kálmán Viktor committed
75
        get_env_variable('DJANG_DB_TYPE', 'postgresql_psycopg2'),
76 77 78 79 80 81 82 83 84 85 86 87 88 89
        'NAME':  get_env_variable('DJANGO_DB_NAME', 'circle'),
        'USER':  get_env_variable('DJANGO_DB_USER', 'circle'),
        'PASSWORD':  get_env_variable('DJANGO_DB_PASSWORD'),
        'HOST': get_env_variable('DJANGO_DB_HOST', ''),
        'PORT': get_env_variable('DJANGO_DB_PORT', ''),
    }
}
########## END DATABASE CONFIGURATION


########## GENERAL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
try:
    with open("/etc/timezone", "r") as f:
Kálmán Viktor committed
90
        systz = f.readline().rstrip()
91 92 93 94 95 96
except:
    systz = None

TIME_ZONE = get_env_variable('DJANGO_TIME_ZONE', default=systz)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code
97 98 99 100 101 102 103
LANGUAGE_CODE = 'en'

# https://docs.djangoproject.com/en/dev/ref/settings/#languages
LANGUAGES = (
    ('en', _('English')),
    ('hu', _('Hungarian')),
)
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

# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n
USE_I18N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n
USE_L10N = True

# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz
USE_TZ = True
########## END GENERAL CONFIGURATION


########## MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = normpath(join(SITE_ROOT, 'media'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = get_env_variable('DJANGO_MEDIA_URL', default='/media/')
########## END MEDIA CONFIGURATION


########## STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'static_collected'))

# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = get_env_variable('DJANGO_STATIC_URL', default='/static/')

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
    normpath(join(SITE_ROOT, 'static')),
)

# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STATIC FILE CONFIGURATION


########## SECRET CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Note: This key should only be used for development and testing.
SECRET_KEY = r"a5w*b0wajigd^kd7b=@w=5=+l_0c62@vljnhzqu3dfc@vx2jw-"
########## END SECRET CONFIGURATION


########## SITE CONFIGURATION
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
########## END SITE CONFIGURATION


########## FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
    normpath(join(SITE_ROOT, 'fixtures')),
)
########## END FIXTURE CONFIGURATION


########## TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.request',
181
    'dashboard.context_processors.notifications',
182
    'dashboard.context_processors.extract_settings',
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs
TEMPLATE_DIRS = (
    normpath(join(SITE_ROOT, 'templates')),
)
########## END TEMPLATE CONFIGURATION


########## MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = (
    # Default Django middleware.
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
204
    'django.middleware.locale.LocaleMiddleware',
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
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
########## END MIDDLEWARE CONFIGURATION


########## URL CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = '%s.urls' % SITE_NAME
########## END URL CONFIGURATION


########## APP CONFIGURATION
DJANGO_APPS = (
    # Default Django apps:
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Useful template tags:
    # 'django.contrib.humanize',

    # Admin panel and documentation:
    'django.contrib.admin',
    # 'django.contrib.admindocs',
)

THIRD_PARTY_APPS = (
    'south',
239 240
    'django_tables2',
    'crispy_forms',
241
    'djcelery',
242
    'sizefield',
243
    'taggit',
244 245 246 247
)

# Apps specific for this project go here.
LOCAL_APPS = (
248
    'common',
249 250 251
    'vm',
    'storage',
    'firewall',
252
    'network',
253
    'dashboard',
254
    'manager',
Őry Máté committed
255
    'acl',
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
)

# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
########## END APP CONFIGURATION


########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
Kálmán Viktor committed
273
    'formatters': {
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        'simple': {
            'format': '%(asctime)s [%(levelname)s]: %(name)s %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
Kálmán Viktor committed
290 291 292
        'syslog': {
            'level': 'INFO',
            'class': 'logging.handlers.SysLogHandler',
293
            'formatter': 'simple',
Kálmán Viktor committed
294 295 296 297
            'address': '/dev/log',
            # 'socktype': SOCK_STREAM,
            # 'address': ('host', '514'),
        }
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', 'syslog'],
            'level': 'INFO',
            'propagate': True,
        },
    }
}
########## END LOGGING CONFIGURATION


########## WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME
########## END WSGI CONFIGURATION
314 315

FIREWALL_SETTINGS = loads(get_env_variable('DJANGO_FIREWALL_SETTINGS'))
316 317

CRISPY_TEMPLATE_PACK = 'bootstrap3'
318 319 320

# format: id: (name, port, protocol)
VM_ACCESS_PROTOCOLS = loads(get_env_variable('DJANGO_VM_ACCESS_PROTOCOLS',
Őry Máté committed
321 322 323
                                             '''{"nx": ["NX", 22, "tcp"],
                                                 "rdp": ["RDP", 3389, "tcp"],
                                                 "ssh": ["SSH", 22, "tcp"]}'''))
324
VM_SCHEDULER = 'manager.scheduler'
325

326
#BROKER_URL = get_env_variable('AMQP_URI')
327

328
#BROKER_URL=get_env_variable('AMQP_URI')
329 330 331

CACHES = {
    'default': {
332
        'BACKEND': 'pylibmc',
333 334
        'LOCATION': '127.0.0.1:11211',
    }
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


if get_env_variable('DJANGO_SAML', 'FALSE') == 'TRUE':
    try:
        from shutil import which  # python >3.4
    except ImportError:
        from shutilwhich import which
    from saml2 import BINDING_HTTP_POST, BINDING_HTTP_REDIRECT

    # INSTALLED_APPS += (  # needed only for testing djangosaml2
    #     'djangosaml',
    # )
    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'djangosaml2.backends.Saml2Backend',
    )

    remote_metadata = join(SITE_ROOT, 'remote_metadata.xml')
    if not isfile(remote_metadata):
        raise ImproperlyConfigured('Download SAML2 metadata to %s' %
                                   remote_metadata)
    required_attrs = loads(get_env_variable('DJANGO_SAML_REQUIRED',
                                            '["uid"]'))
    optional_attrs = loads(get_env_variable('DJANGO_SAML_OPTIONAL',
                                            '["mail", "cn", "sn"]'))

    SAML_CONFIG = {
        'xmlsec_binary': which('xmlsec1'),
        'entityid': DJANGO_URL + 'saml2/metadata/',
        'attribute_map_dir': join(SITE_ROOT, 'attribute-maps'),
        'service': {
            'sp': {
                'name': SITE_NAME,
                'endpoints': {
                    'assertion_consumer_service': [
                        (DJANGO_URL + 'saml2/acs/', BINDING_HTTP_POST),
                    ],
                    'single_logout_service': [
                        (DJANGO_URL + 'saml2/ls/', BINDING_HTTP_REDIRECT),
                    ],
                },
                'required_attributes': required_attrs,
                'optional_attributes': optional_attrs,
            },
        },
        'metadata': {'local': [remote_metadata], },
        'key_file': join(SITE_ROOT, 'samlcert.key'),  # private part
        'cert_file': join(SITE_ROOT, 'samlcert.pem'),  # public part
    }
    try:
        SAML_CONFIG += loads(get_env_variable('DJANGO_SAML_SETTINGS'))
    except ImproperlyConfigured:
        pass
    SAML_CREATE_UNKNOWN_USER = True
    SAML_ATTRIBUTE_MAPPING = loads(get_env_variable(
        'DJANGO_SAML_ATTRIBUTE_MAPPING',
        '{"mail": ["email"], "sn": ["last_name"], '
        '"uid": ["username"], "cn": ["first_name"]}'))
394 395 396 397 398
    SAML_GROUP_ATTRIBUTES = get_env_variable(
        'DJANGO_SAML_GROUP_ATTRIBUTES', '').split(',')
    SAML_GROUP_OWNER_ATTRIBUTES = get_env_variable(
        'DJANGO_SAML_GROUP_OWNER_ATTRIBUTES', '').split(',')

399
    SAML_CREATE_UNKNOWN_USER = True
400
    if get_env_variable('DJANGO_SAML_ORG_ID_ATTRIBUTE', False) is not False:
401 402
        SAML_ORG_ID_ATTRIBUTE = get_env_variable(
            'DJANGO_SAML_ORG_ID_ATTRIBUTE')
403 404

LOGIN_REDIRECT_URL = "/"
405 406

LOCALE_PATHS = (join(SITE_ROOT, 'locale'), )
Kálmán Viktor committed
407
COMPANY_NAME = "BME IK 2014"