"""
Django settings for webapps project.

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

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

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

import hashlib
import os
import sys
from datetime import timedelta

from django.utils.translation import gettext_lazy as _
from logging.handlers import SysLogHandler

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

# SECURITY WARNING: don't run with debug turned on in production!
DEFAULT_SECRET_KEY_FOR_TESTING_ONLY = '9fk7v#1t(&%q0$o=apfeanjb8t5g8#og)etnwqs@f+!chw*v92'
DEFAULT_FERNET_KEY_FOR_TESTING_ONLY = 'sec8Q1_Za4bAjfFtEC9AvH6ctZ3hlEiEIGGNZPOBSlI='
DEFAULT_CAS_SALT_FOR_TESTING_ONLY = 'pt33-5exSbk7-Az85e77CZ-yUtrujsZ'

# Override this block in real environment
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-varda-cacher',
    }
}
ALLOWED_HOSTS = ['*']
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = DEFAULT_SECRET_KEY_FOR_TESTING_ONLY

DEFAULT_CACHE_INVALIDATION_TIME = 54000  # 15 hours
SESSION_COOKIE_AGE = 43200  # 12 hours
FERNET_SECRET_KEY = os.getenv('FERNET_SECRET_KEY', DEFAULT_FERNET_KEY_FOR_TESTING_ONLY)

OPETUSHALLITUS_ORGANISAATIO_OID = '1.2.246.562.10.00000000001'
OPH_USER_LIMIT = 6
STAFF_USER_LIMIT = 9

# Application definition
# In order to preserve the content-types in the DB,
# always add new apps to the bottom of the list
INSTALLED_APPS = [
    'crispy_forms',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django_filters',
    'guardian',
    'rest_framework',
    'simple_history',
    'varda.apps.VardaConfig',
    'django_celery_results',
    'django_celery_beat',
    'django_cas_ng',
    'knox',
    'log_request_id',
    'corsheaders',
    'token_resolved',
    'django.contrib.postgres',
    'drf_yasg',
    'django_spaghetti',
]

MIDDLEWARE = [
    'varda.custom_middleware.SensitiveMiddleware',
    'varda.custom_middleware.ValidateCASProxyURL',
    'log_request_id.middleware.RequestIDMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'token_resolved.middleware.AddTokenHeaderMiddleware',
    'csp.middleware.CSPMiddleware',
    'varda.custom_middleware.AdditionalHeadersMiddleware',
    'simple_history.middleware.HistoryRequestMiddleware'
]

ROOT_URLCONF = 'webapps.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'webapps.wsgi.application'

# Access-Control-Allow-Origin
# https://github.com/ottoyiu/django-cors-headers/
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = ['http://localhost:4200']


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

def get_test_db_name():
    md5 = hashlib.md5()
    md5.update(os.environ.get('BUILD_TAG', 'no-tag').encode('utf-8'))
    return md5.hexdigest()


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('POSTGRESQL_DATABASE', 'varda_db'),
        'USER': os.getenv('POSTGRESQL_USER', 'varda_admin'),
        'PASSWORD': os.getenv('POSTGRESQL_PASSWORD', 'localhero'),
        'HOST': os.getenv('POSTGRESQL_SERVICE_HOST', 'localhost'),
        'PORT': os.getenv('POSTGRESQL_SERVICE_PORT', '5432'),
        'TEST': {
            'NAME': get_test_db_name(),
        },
    }
}

TESTING = sys.argv[1:2] == ['test']

# Default primary key field
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

# These were added when django-guardian was added
# https://github.com/django-guardian/django-guardian

AUTHENTICATION_BACKENDS = (
    'varda.custom_auth.PasswordExpirationModelBackend',  # default override
    'guardian.backends.ObjectPermissionBackend',
    'varda.cas.cas_components.OppijaCASBackend',  # Before CASBackend because has view check
    'varda.cas.cas_components.CASBackend',
)
ANONYMOUS_USER_NAME = 'anonymous'
ANONYMIZATION_CHECKER_USER_NAME = 'varda_anonymisointi_tarkistus'

# Password validation
# https://docs.djangoproject.com/en/dev/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',
    },
]


# Django logging

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'request_id': {
            '()': 'log_request_id.filters.RequestIDFilter'
        },
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
        'require_prod_env': {
            '()': 'webapps.logging.ProductionFilter',
        },
    },
    'formatters': {
        'verbose': {
            '()': 'webapps.logging.SensitiveFormatter',
            'format': '%(process)-5d %(thread)d [%(request_id)s] "%(request_host)s" %(name)-50s %(levelname)-8s %(message)s'
        },
        'simple': {
            '()': 'webapps.logging.SensitiveFormatter',
            'format': '[%(asctime)s] %(name)s %(levelname)s %(message)s',
            'datefmt': '%d/%b/%Y %H:%M:%S'
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'syslog': {
            'level': 'INFO',
            'filters': ['require_debug_false', 'request_id'],
            'class': 'logging.handlers.SysLogHandler',
            'facility': SysLogHandler.LOG_LOCAL1,
            'address': ['127.0.0.1', 1514],
            'formatter': 'verbose'
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_prod_env'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        },
        'mail_admins_security': {
            'level': 'WARNING',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True
        }
    },
    'loggers': {
        '': {
            'handlers': ['syslog', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'gunicorn': {
            'handlers': ['mail_admins', 'syslog', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'celery': {
            'handlers': ['mail_admins', 'syslog', 'console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'celery.beat': {
            'handlers': ['mail_admins', 'syslog', 'console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'django': {
            'handlers': ['syslog', 'console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'level': 'ERROR',
            'handlers': ['syslog', 'console'],
            'propagate': False,
        },
        'django.security': {
            'level': 'WARNING',
            'handlers': ['mail_admins_security'],
            'propagate': False,
        },
        'django.server': {
            'level': 'ERROR',
            'handlers': ['syslog', 'console'],
            'propagate': False,
        },
        'webapps.celery': {
            'handlers': ['mail_admins', 'syslog', 'console'],
            'level': 'WARNING',
            'propagate': False,
        }
    }
}


"""
API-Throttling:
- 10/second was not enough for local tests -> HTTP/1.1 429 Too Many Requests,
  therefore disable throttling for tests:
"""
if 'test' in sys.argv:
    CACHES['default'] = {'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }

CUSTOM_LOGIN_RATELIMIT = {
    'header_x_real_ip': '50/h',
    'post_form': '4/h'
}

# TODO:_Set the strict-throttles to very strict, after initial loading has been performed. This is important for security reasons!
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'varda.custom_renderer.ShowFiltersBrowsableAPIRenderer',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'varda.custom_auth.CustomSessionAuthentication',
        'varda.custom_auth.CustomTokenAuthentication',
        'varda.custom_auth.CustomBasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',
        'webapps.api_throttles.BurstRateThrottle',
        'webapps.api_throttles.SustainedGetRateThrottle'
    ),
    'DEFAULT_THROTTLE_RATES': {
        'anon': '10/hour',
        'burst': '20/second',
        'sustained_get': '100000/day',
        'sustained_modify': '100000/day',
        'burst_strict': '5/second',
        'sustained_strict': '500/day',
        'public': '50/hour',
        'auth': '10/hour',
        # Bigger rate for token authentication as it is essential for integrations and integrations sometimes send
        # invalid tokens
        'auth_token': '100/hour'
    },
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'PAGE_SIZE': 20,
    'HTML_SELECT_CUTOFF': 200,
    'EXCEPTION_HANDLER': 'varda.exception_handler.varda_exception_handler',
}

REST_KNOX = {
    'TOKEN_TTL': timedelta(hours=24),
    'AUTH_HEADER_PREFIX': 'Token',
    'TOKEN_LIMIT_PER_USER': 10
}


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

# Language set to English because in unit tests that is the assumed language
# Django's LocaleMiddleware is disabled so that error messages are always in English and predictable

USE_I18N = True
LANGUAGE_CODE = 'en'
LANGUAGES = [
    ('en', _('English'))
]
LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale'),
]

USE_TZ = True
TIME_ZONE = 'UTC'


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

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'rest_framework', 'static'),
]
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'


# Swagger (online API documentation)

SWAGGER_SETTINGS = {
    'VALIDATOR_URL': None,
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
        }
    },
    'LOGOUT_URL': '/api-auth/logout/',
    'DEFAULT_AUTO_SCHEMA_CLASS': 'varda.custom_swagger.ReadWriteAutoSchema',
}

LOGIN_URL = 'rest_framework:login'
LOGOUT_URL = 'rest_framework:logout'

LOGIN_REDIRECT_URL = '/'
SITE_ID = 1

CRISPY_TEMPLATE_PACK = 'bootstrap3'


# Content-Secure Policy, Keep our policy as strict as possible
# Strict nonce policy for scripts https://csp.withgoogle.com/docs/strict-csp.html
# Impossible to implement strict policy for styles, fonts and images as there are many places that do not support it,
# e.g. Django admin, DRF yasg/Swagger and DRF browsable API
CSP_INCLUDE_NONCE_IN = ('script-src',)
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", 'maxcdn.bootstrapcdn.com', 'fonts.googleapis.com',)
CSP_FONT_SRC = ("'self'", 'maxcdn.bootstrapcdn.com', 'fonts.gstatic.com',)
CSP_IMG_SRC = ("'self'", 'data:')
CSP_OBJECT_SRC = ("'none'",)
CSP_BASE_URI = ("'none'",)

CSRF_COOKIE_HTTPONLY = True

if 'VARDA_ENVIRONMENT_TYPE' not in os.environ:
    # Celery configuration for local dev server. Override this block in real environment
    BROKER_BACKEND = 'memory'
    CELERY_TASK_ALWAYS_EAGER = True
    CELERY_TASK_EAGER_PROPAGATES = True


# Opintopolku. Override this block in real environment
OPINTOPOLKU_DOMAIN = 'https://virkailija.testiopintopolku.fi'
OPPIJA_OPINTOPOLKU_DOMAIN = 'https://testiopintopolku.fi'
PRODUCTION_ENV = False
QA_ENV = False


# CAS-authentication (OPH autentikointipalvelu)
CAS_SERVER_URL = OPINTOPOLKU_DOMAIN + '/cas/'
CAS_CREATE_USER = True
CAS_LOGIN_MSG = None
CAS_LOGGED_MSG = None
CAS_VERSION = 3
CAS_RETRY_LOGIN = False
# Hide salt from debug report https://docs.djangoproject.com/en/4.0/ref/settings/#std:setting-DEBUG
CAS_API_SALT = os.environ.get('VARDA_SALT', DEFAULT_CAS_SALT_FOR_TESTING_ONLY)
# Validation hash must be in header CAS_NEXT_HASH
CAS_ACCEPT_PROXY_URL_FROM_HEADER = 'CAS_NEXT'

# CAS-oppija-authentication (OPH autentikointipalvelu) see cas_settings.py for mapping
OPPIJA_CAS_SERVER_URL = OPPIJA_OPINTOPOLKU_DOMAIN + '/cas-oppija/'
OPPIJA_CAS_APPLY_ATTRIBUTES_TO_USER = True

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Allas s3
ALLAS_USER_FILES_BUCKET = None

# Excel/Java settings
EXCEL_PATH = f'{BASE_DIR}/excel_reports/'
JAVA_URL = 'http://localhost:8080'

# POST parameters that are replaced in error messages
SENSITIVE_POST_PARAMETERS = ['password']

"""
TODO: This does not currently work. Login fails with 403 forbidden.
if 'VARDA_HOSTNAME' in os.environ:
    CAS_PROXY_CALLBACK = 'https://' + os.environ['VARDA_HOSTNAME'] + '/accounts/callback'  # The full url to the callback view
"""

# Extend these default settings with optional settings_environment.py file
try:
    from .settings_environment import *  # noqa: F403,F401
except ModuleNotFoundError:
    pass
