# -*- encoding: utf-8 -*-

# Django settings for pffedportal project

DEBUG = False
LOG_DEBUG = False
TEMPLATE_DEBUG = DEBUG
USE_DEBUG_TOOLBAR = False

import os
import re
import xml.etree.ElementTree as ET

_PROJECT_PATH = os.path.join(os.path.dirname(__file__))

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']

MANAGERS = ADMINS

_DATABASE_NAME = os.path.join(_PROJECT_PATH, 'pffedportal.db')
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': _DATABASE_NAME,
    }
}

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

SITE_ID = 1

# 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

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(_PROJECT_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/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'

# Static files (see server.document-root in lighttpd configuration)
STATIC_ROOT = '/usr/local/univnautes/www/static'
STATIC_URL = '/static/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'w5c+cpf&qhxpx0=)nwe26h0&t$dgngp*sd6y++s!6@uy3f52#4'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

ROOT_URLCONF = 'pffedportal.urls'

# templates from univnautes
TEMPLATE_DIRS = (
    '/var/lib/univnautes/templates/',
    os.path.join(_PROJECT_PATH, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # pffedportal:
    'authentic2.idp',
    'authentic2.attribute_aggregator',
    'base',
)

SESSION_COOKIE_NAME = 'pffedportalsessionid'

SESSION_ENGINE = 'django.contrib.sessions.backends.file'
SESSION_FILE_PATH = '/var/tmp/pffedportalsessions'
try:
    os.mkdir(SESSION_FILE_PATH)
except:
    pass


AUTH_FRONTENDS = ('authentic2.authsaml2.frontend.AuthSAML2Frontend',)
INSTALLED_APPS += ('authentic2.saml','authentic2.authsaml2',)
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'authentic2.authsaml2.backends.AuthSAML2PersistentBackend',
    'authentic2.authsaml2.backends.AuthSAML2TransientBackend')


SAML_SIGNATURE_PUBLIC_KEY = '''-----BEGIN CERTIFICATE-----
MIIDIzCCAgugAwIBAgIJANUBoick1pDpMA0GCSqGSIb3DQEBBQUAMBUxEzARBgNV
BAoTCkVudHJvdXZlcnQwHhcNMTAxMjE0MTUzMzAyWhcNMTEwMTEzMTUzMzAyWjAV
MRMwEQYDVQQKEwpFbnRyb3V2Z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Rv2ye3Dted1WkUL4WYPxccVhLWKITi
rRtqB03o8m3pG3kJnUr0LIzu0px5J/o8iH3ZOJOTE3iBa+uI/KHmxygc2H+XPGFa
HGeAxuJCNO2kAN0Losbnz5dlAoGAVsCn94gGWPxSjxA0PC7zpTYVnZdwOjbPr/pO
LDE0cEY9GBq98JjrwEd77KibmVMm+Z4uaaT0jXiYhl8pyJ5IFwUS13juCbo1z/u/
ldMoDvZ8/R/MexTA/1204u/mBecMJiO/jPw3GdIJ5phv2omHe1MSuSNsDfN8Sbap
gmsgaiMCgYB/nrTk89Fp7050VKCNnIt1mHAcO9cBwDV8qrJ5O3rIVmrg1T6vn0aY
wRiVcNacaP+BivkrMjr4BlsUM6yH4MOBsNhLURiiCL+tLJV7U0DWlCse/doWij4U
TKX6tp6oI+7MIJE6ySZ0cBqOiydAkBePZhu57j6ToBkTa0dbHjn1WA==
-----END RSA PRIVATE KEY-----'''

LOCAL_METADATA_CACHE_TIMEOUT = 600

SAML_METADATA_ROOT = 'metadata'

# Can be none, sp, idp or both
SAML_METADATA_AUTOLOAD = 'none'

#
# pfSense / univnautes relationship
#

# fastcgi (see http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/)
FORCE_SCRIPT_NAME=""

# eduPersonTargetedId blacklist (nameid|issuerid)
USERBL = '/var/lib/univnautes/userbl'

# parameters from pfSense (/conf/config.xml)
f = open('/conf/config.xml','r')
root = ET.fromstring(f.read())
f.close()

# get timezone from config.xml
try:
    TIME_ZONE = root.find('system/timezone').text
except:
    TIME_ZONE = 'Europe/Paris'

# hostname for the https url
try:
    HTTPS_HOSTNAME = root.find('captiveportal/httpsname').text
except:
    HTTPS_HOSTNAME = 'univnautes.entrouvert.lan'

try:
    SAML_SIGNATURE_PUBLIC_KEY = root.find('installedpackages/univnautes/config/samlcrt').text.decode('base64')
    SAML_SIGNATURE_PRIVATE_KEY = root.find('installedpackages/univnautes/config/samlkey').text.decode('base64')
except:
    pass

# default IdP
try:
    DEFAULT_IDP = root.find('installedpackages/univnautes/config/defaultidp').text
except:
    DEFAULT_IDP = 'https://services-federation.renater.fr/test/idp'

# SESSION_COOKIE_AGE from pfsenseid, at least 2 minutes
try:
    SESSION_COOKIE_AGE = max(int(root.find('captiveportal/idletimeout').text)*60, 2*60)
except:
    SESSION_COOKIE_AGE = 15*60

# discovery service
try:
    stores = root.find('installedpackages/univnautes/config/discostoresread').text.decode('base64').decode('iso-8859-1').splitlines()
    DISCO_STORES_READ = [ l for l in stores if not re.match('^\s*$', l) ]
except:
    DISCO_STORES_READ = [ ]

try:
    stores = root.find('installedpackages/univnautes/config/discostoreswrite').text.decode('base64').decode('iso-8859-1').splitlines()
    DISCO_STORES_WRITE = [ l for l in stores if not re.match('^\s*$', l) ]
    if not DISCO_STORES_WRITE:
        DISCO_STORES_WRITE = DISCO_STORES_READ
except:
    DISCO_STORES_WRITE = DISCO_STORES_READ

# After login, redirect the user to the original requested URL after this delay (in seconds).
# 0 = immediate redirection
# -1 = no redirection
try:
    REDIRECT_DELAY = int(root.find('installedpackages/univnautes/config/redirectdelay').text)
except:
    REDIRECT_DELAY = -1

# force redirection to this URL after login (supersede next_url)
try:
    REDIRECT_URL = root.find('installedpackages/univnautes/config/redirecturl').text
except:
    REDIRECT_URL = None

# don't handle these URLs
try:
    firsturlbl = root.find('installedpackages/univnautes/config/firsturlbl').text.decode('base64').decode('iso-8859-1').splitlines()
    FIRST_URL_BLACKLIST = [ u for u in firsturlbl if not re.match('^\s*($|#)', u) ]
except:
    FIRST_URL_BLACKLIST = []

# /mail form
try:
    EMAIL_RCPT = root.find('installedpackages/univnautestexts/config/email_rcpt').text
except:
    EMAIL_RCPT = None

try:
    subjects = root.find('installedpackages/univnautestexts/config/email_subjects').text.decode('base64').decode('iso-8859-1').splitlines()
    EMAIL_SUBJECTS = [ l for l in subjects if not re.match('^\s*$', l) ]
except:
    EMAIL_SUBJECTS = (
            u"Je ne trouve pas mon établissement dans la liste",
            u"Quand je clique sur mon établissement, il ne se passe rien",
            u"L'interface est peu lisible",
            u"Autre (précisez dans la description)",
            )

try:
    EMAIL_HOST = root.find('installedpackages/univnautestexts/config/email_host').text
except:
    EMAIL_HOST = None

try:
    EMAIL_PORT = int(root.find('installedpackages/univnautestexts/config/email_port').text)
except:
    EMAIL_PORT = 587

try:
    EMAIL_HOST_USER = root.find('installedpackages/univnautestexts/config/email_host_user').text
except:
    EMAIL_HOST_USER = None

try:
    EMAIL_HOST_PASSWORD = root.find('installedpackages/univnautestexts/config/email_host_password').text
except:
    EMAIL_HOST_PASSWORD = None

try:
    if root.find('installedpackages/univnautestexts/config/email_use_tls').text == None:
        EMAIL_USE_TLS = False
    else:
        EMAIL_USE_TLS = True
except:
    EMAIL_USE_TLS = True

try:
    GEO_START_BOUNDS = root.find('installedpackages/univnautestexts/config/start_bounds').text
except:
    GEO_START_BOUNDS = "[[41.1,-5.53],[51.5,9.91]]"


# local_settings.py can be used to override environment-specific settings
# like database and email that differ between development and production.
try:
    from local_settings import *
except ImportError:
    pass

# nasty logs...
if LOG_DEBUG:
    DISPLAY_MESSAGE_ERROR_PAGE = True

if USE_DEBUG_TOOLBAR:
    MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
    INSTALLED_APPS += ('debug_toolbar',)

