Skip to content
Snippets Groups Projects
settings.py 9.55 KiB
Newer Older
"""
Django settings for iric_data project.

Generated by 'django-admin startproject' using Django 2.1.4.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os
import sys
import ldap
from decouple import Csv, config
from django_auth_ldap.config import GroupOfNamesType, LDAPSearch

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

FILE_UPLOAD_PERMISSIONS = 0o640

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
# CSRF_USE_SESSIONS = True
# CSRF_COOKIE_SECURE = True

ADMINS = config('ADMINS', cast=lambda s: [(a[0], a[1]) for x in s.split(',') for a in [x.strip().split('/')]])

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
    'django.contrib.postgres',
    'social_django',
    'crispy_forms',
    'chartjs',
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
    'private_storage',
Jonathan Seguin's avatar
Jonathan Seguin committed
    'loginas',
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
# See https://pypi.org/project/django-private-storage/ for info on Private Storage

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

ROOT_URLCONF = 'iric_data.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'portal/templates'), BASE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                'portal.context_processors.app_settings',
                'portal.context_processors.utils',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'

WSGI_APPLICATION = 'iric_data.wsgi.application'

# Graphene / GraphQL
GRAPHENE = {
    "ATOMIC_MUTATIONS": True,
}

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': config('DB_ENGINE'),
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT', default=5432),
    }
}

if 'test' in sys.argv:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    DATABASES['default']['NAME'] = os.path.join(BASE_DIR, 'db.sqlite3')

# For local development purposes
if 'sqlite3' in DATABASES['default']['ENGINE']:
    DATABASES['default']['NAME'] = os.path.join(BASE_DIR, 'db.sqlite3')


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


AUTHENTICATION_BACKENDS = [
    'social_core.backends.azuread_tenant.AzureADTenantOAuth2',
    'django.contrib.auth.backends.ModelBackend',
    'django_auth_ldap.backend.LDAPBackend',
    'portal.auth_backends.TokenAuthBackend',
SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.social_auth.associate_by_email',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    # 'social_core.pipeline.debug.debug'
SOCIAL_AUTH_URL_NAMESPACE = 'social'
Jonathan Seguin's avatar
Jonathan Seguin committed
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = config('SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY', default=None)  # App ID
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = config('SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET', default=None)  # App Secret
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = config('SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID', default=None)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_EXTRA_DATA = ['groups', 'onPremisesSamAccountName']
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'login-success'
LOGOUT_REDIRECT_URL = 'index'
LOGOUT_URL = 'logout'
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
# Sessions ########################
SESSION_COOKIE_AGE = config('SESSION_COOKIE_AGE', default=86400, cast=int)

# django-auth-ldap ##############################
AUTH_LDAP_SERVER_URI = config('AUTH_LDAP_SERVER_URI')
AUTH_LDAP_USER_QUERY_FIELD = 'email'
AUTH_LDAP_BIND_DN = config('AUTH_LDAP_BIND_DN', default=None)
AUTH_LDAP_BIND_PASSWORD = config('AUTH_LDAP_BIND_PASSWORD', default=None)
AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = config('AUTH_LDAP_BIND_AS_AUTHENTICATING_USER', cast=bool)
AUTH_LDAP_USER_DN_TEMPLATE = config('AUTH_LDAP_USER_DN_TEMPLATE')
AUTH_LDAP_USER_SEARCH = LDAPSearch(config('AUTH_LDAP_SEARCH'), ldap.SCOPE_SUBTREE, "(|(samaccountname=%(user)s)(mail=%(user)s))")
AUTH_LDAP_USER_ATTR_MAP = {
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
    "username": "mail"
}
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(config('AUTH_LDAP_SEARCH'), ldap.SCOPE_SUBTREE, "(objectClass=group)(name=iric-*)")
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
AUTH_LDAP_CACHE_GROUPS = False
AUTH_LDAP_STAFF_GROUP = config('AUTH_LDAP_STAFF_GROUP')

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_staff": AUTH_LDAP_STAFF_GROUP
}
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed

AUTH_LDAP_PI_GROUP = config('AUTH_LDAP_PI_GROUP', default='iric-PI')
AUTH_LDAP_MIRROR_GROUPS = True

COMPUTER_DOMAIN = config('COMPUTER_DOMAIN')

if DEBUG:
    import logging
    import logging.handlers
    logfile = "/tmp/django-ldap-debug.log"
    ldap_logger = logging.getLogger('django_auth_ldap')
    ldap_logger.setLevel(logging.DEBUG)
    handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=1024 * 500, backupCount=5)
    ldap_logger.addHandler(handler)
# end django-auth-ldap ############################

# Email #########################################
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.umontreal.ca'
EMAIL_PORT = '25'
DEFAULT_FROM_EMAIL = 'webmaster@iric.ca'
SERVER_EMAIL = DEFAULT_FROM_EMAIL
EMAIL_REPLYTO = DEFAULT_FROM_EMAIL
EMAIL_FROM = DEFAULT_FROM_EMAIL

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'fr'

LANGUAGES = [
    ('fr', 'French'),
    ('en', 'English')
]


TIME_ZONE = 'America/Toronto'
USE_I18N = True
USE_L10N = True
USE_TZ = True

ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
MEDIA_URL = "/media/"

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/html/static/'

if not DEBUG:
    STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'

Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
# FILE PATHS
DATA_ROOT = config('DATA_ROOT')
Jean-Philippe Laverdure's avatar
Jean-Philippe Laverdure committed
PRIVATE_STORAGE_ROOT = DATA_ROOT
PRIVATE_STORAGE_AUTH_FUNCTION = 'private_storage.permissions.allow_staff'

# LOGGING
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'formatters': {
        'verbose': {
            'format': '[%(levelname)s %(asctime)s %(module)s] %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '[%(levelname)s %(module)s] %(message)s'
        },
    },
    'loggers': {
        'debug': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
        },
    },
}

if not DEBUG:
    LOGGING['handlers'].update({
        'applogfile': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(ENV_PATH, 'IRIC_DATA.log'),
            'maxBytes': 1024 * 1024 * 15,  # 15MB
            'backupCount': 10,
            'formatter': 'verbose'
        }
    })

    LOGGING['loggers'].update({
        'django.request': {
            'handlers': ['applogfile'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
        }
    })