Skip to content
Snippets Groups Projects
Select Git revision
  • 39f9919cf0165c97d00a7d3e38dd05d514fe9531
  • master default protected
  • pipeline
  • dev
  • quality
  • docs
  • issue-65
  • issue-30
  • issue-19
  • issue-28
  • 0.1.1
  • 0.1.0
12 results

settings.py

Blame
  • settings.py 9.80 KiB
    # TODO describe all required / optional settings
    """
    Django settings for the PEDASI project.
    
    Generated by 'django-admin startproject' using Django 2.0.8.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/2.0/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.0/ref/settings/
    
    For guidance on configuration for production deployment, see
    https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
    
    
    Configuration
    =============
    
    Certain configuration properties are read from a '.env' file in the project root directory.
    These properties are:
    
    SECRET_KEY - required
      Django secret key - a randomly generated character sequence.
    
    DEBUG
      Run the server in debug mode?
      Default is 'false'.
    
    ALLOWED_HOSTS - required if not in debug mode
      List of hostnames on which the server is permitted to run
    
    DATABASE_URL
      URL to default SQL database - in `dj-database-url <https://github.com/kennethreitz/dj-database-url>`_ format.
      Default is SQLite3 'db.sqlite3' in project root directory.
    
    PROV_DATABASE_NAME
      Name of MongoDB database in which to store PROV data.
      Default is 'prov'.
    
    """
    
    
    import os
    
    from django.urls import reverse_lazy
    
    from decouple import config, Csv
    import dj_database_url
    import mongoengine
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    # 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', default=False, cast=bool)
    
    ALLOWED_HOSTS = config('ALLOWED_HOSTS',
                           cast=Csv(),
                           default='*' if DEBUG else '127.0.0.1,localhost.localdomain,localhost')
    
    # Application definition
    
    DJANGO_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
    THIRD_PARTY_APPS = [
        'corsheaders',
        'bootstrap4',
        'haystack',
        'rest_framework',
        'rest_framework.authtoken',
        'social_django',
    ]
    
    CUSTOM_APPS = [
        'profiles.apps.ProfilesConfig',  # Refer to AppConfig directly since we override the .ready() method
        'applications',
        'datasources.apps.DatasourcesConfig',
        'provenance',
        'core',
        'api',
    ]
    
    # Custom apps have to be listed before Django apps so they override default templates
    INSTALLED_APPS = CUSTOM_APPS + THIRD_PARTY_APPS + DJANGO_APPS
    
    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'pedasi.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'pedasi', 'templates')],
            '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',
                    'social_django.context_processors.backends',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'pedasi.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases
    
    DATABASES = {
        'default': config(
            'DATABASE_URL',
            default='mysql://pedasi:pedasi@localhost:3306/pedasi',
            cast=dj_database_url.parse
        ),
    }
    
    mongoengine.register_connection(
        host=config(
            'PROV_DATABASE_URL',
            default='mongodb://localhost/prov',
        ),
        alias='default'
    )
    
    mongoengine.register_connection(
        host=config(
            'INTERNAL_DATABASE_URL',
            default='mongodb://localhost/internal_data'
        ),
        alias='internal_data',
    )
    
    
    # Search backend
    
    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
            'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        }
    }
    
    HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
    
    
    # Password validation
    # https://docs.djangoproject.com/en/2.0/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',
        },
    ]
    
    
    # Social auth app configuration
    
    SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', default=None)
    SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', default=None)
    
    AUTHENTICATION_BACKENDS = [
        'django.contrib.auth.backends.ModelBackend',
    ]
    
    if SOCIAL_AUTH_GOOGLE_OAUTH2_KEY is not None and SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET is not None:
        AUTHENTICATION_BACKENDS += [
            'social_core.backends.google.GoogleOAuth2',
        ]
    
    SOCIAL_AUTH_PIPELINE = [
        # Get the information we can about the user and return it in a simple
        # format to create the user instance later. On some cases the details are
        # already part of the auth response from the provider, but sometimes this
        # could hit a provider API.
        'social_core.pipeline.social_auth.social_details',
    
        # Get the social uid from whichever service we're authing thru. The uid is
        # the unique identifier of the given user in the provider.
        'social_core.pipeline.social_auth.social_uid',
    
        # Verifies that the current auth process is valid within the current
        # project, this is where emails and domains whitelists are applied (if
        # defined).
        'social_core.pipeline.social_auth.auth_allowed',
    
        # Checks if the current social-account is already associated in the site.
        'social_core.pipeline.social_auth.social_user',
    
        # Make up a username for this person, appends a random string at the end if
        # there's any collision.
        'social_core.pipeline.user.get_username',
    
        # Send a validation email to the user to verify its email address.
        # Disabled by default.
        # 'social_core.pipeline.mail.mail_validation',
    
        # Associates the current social details with another user account with
        # a similar email address. Disabled by default.
        # 'social_core.pipeline.social_auth.associate_by_email',
    
        # Create a user account if we haven't found one yet.
        # 'social_core.pipeline.user.create_user',
        'profiles.social_auth.create_user_disabled',
    
        # Create the record that associates the social account with the user.
        'social_core.pipeline.social_auth.associate_user',
    
        # Populate the extra_data field in the social record with the values
        # specified by settings (and the default ones like access_token, etc).
        'social_core.pipeline.social_auth.load_extra_data',
    
        # Update the user record with any changed info from the auth service.
        'social_core.pipeline.user.user_details',
    
        # Email admins to activate the account
        'profiles.social_auth.email_admins',
    ]
    
    SOCIAL_AUTH_LOGIN_REDIRECT_URL = reverse_lazy('index')
    LOGIN_REDIRECT_URL = reverse_lazy('index')
    SOCIAL_AUTH_INACTIVE_USER_URL = reverse_lazy('profiles:inactive')
    
    
    # Use Argon2 as hashing algorithm for new passwords
    
    PASSWORD_HASHERS = [
        'django.contrib.auth.hashers.Argon2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
        'django.contrib.auth.hashers.BCryptPasswordHasher',
    ]
    
    # Set custom user model
    AUTH_USER_MODEL = 'profiles.User'
    
    LOGIN_URL = reverse_lazy('profiles:login')
    
    
    # Application API config
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            # Authenticate using tokens for normal API use
            'rest_framework.authentication.TokenAuthentication',
            # Allow logged in users to explore the API through the PEDASI web interface
            'rest_framework.authentication.SessionAuthentication',
        ],
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ]
    }
    
    # Add CORS exemption to API endpoints
    
    CORS_ORIGIN_ALLOW_ALL = True
    
    CORS_URLS_REGEX = r'^/api/.*$'
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/
    
    LANGUAGE_CODE = 'en-gb'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/
    
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'pedasi', 'static'),
        os.path.join(BASE_DIR, 'docs', 'build'),
    ]
    
    
    # Email provider for notification emails
    EMAIL_HOST = config('EMAIL_HOST', default=None)
    EMAIL_PORT = config('EMAIL_PORT', cast=int, default=25)
    
    EMAIL_HOST_USER = config('EMAIL_HOST_USER', default=None)
    EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default=None)
    DEFAULT_FROM_EMAIL = config('DEFAULT_FROM_EMAIL', default=EMAIL_HOST_USER)
    
    EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool, default=False)
    EMAIL_USE_SSL = config('EMAIL_USE_SSL', cast=bool, default=False)
    
    EMAIL_SUBJECT_PREFIX = '[PEDASI]'
    
    if DEBUG and not EMAIL_HOST:
        EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
        EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'mail')
    
    ADMINS = [val.split('|') for val in config('ADMINS', cast=Csv(), default='')]