<reponame>chmvh/chmvh-website
"""
Django settings for chmvh_website project.

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

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

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


def env_bool(name: str) -> bool:
    raw_value = os.getenv(name, "")

    return raw_value.lower() == "true"


def env_list(name: str) -> list[str]:
    raw_value = os.getenv(name, "")

    if not raw_value:
        return []

    return raw_value.split(",")


SILENCED_SYSTEM_CHECKS = []


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


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

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env_bool("CHMVH_DEBUG")

SECRET_KEY = os.getenv("CHMVH_SECRET_KEY")
if DEBUG and not SECRET_KEY:
    SECRET_KEY = "debug"

ALLOWED_HOSTS = env_list("CHMVH_ALLOWED_HOSTS")


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.messages",
    "django.contrib.sessions",
    "django.contrib.sitemaps",
    "django.contrib.staticfiles",
    # Third Party Apps
    "adminsortable2",
    "captcha",
    "rest_framework",
    "sass_processor",
    "solo",
    # Custom Apps
    "common",
    "configuration",
    "contact",
    "gallery",
    "resources",
    "staticpages",
    "team",
]

MIDDLEWARE = [
    "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 = "chmvh_website.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",
                "common.context_processors.analytics",
                "configuration.context_processors.practice_info",
            ],
        },
    },
]

WSGI_APPLICATION = "chmvh_website.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "HOST": os.getenv("CHMVH_DB_HOST", "localhost"),
        "PORT": os.getenv("CHMVH_DB_PORT", "5432"),
        "USER": os.getenv("CHMVH_DB_USER", "postgres"),
        "PASSWORD": os.getenv("CHMVH_DB_PASSWORD"),
        "NAME": os.getenv("CHMVH_DB_NAME", "postgres"),
    }
}

if os.getenv("CHMVH_TEST"):
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": ":memory:",
        }
    }


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

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",  # noqa
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",  # noqa
    },
]


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

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_ROOT = os.getenv('CHMVH_STATIC_ROOT')
STATIC_URL = "/static/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "sass_processor.finders.CssFinder",
]

# Media Files (User Uploaded)

# This is only used for development when we're not uploading files to S3.
MEDIA_ROOT = os.getenv("CHMVH_MEDIA_ROOT", os.path.join(BASE_DIR, "media"))
MEDIA_URL = "/media/"

# HTTPS
if env_bool("CHMVH_HTTPS"):
    CSRF_COOKIE_HTTPONLY = True
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True

    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_SSL_REDIRECT = True
    X_FRAME_OPTIONS = "DENY"


# Email Settings
DEFAULT_FROM_EMAIL = "<EMAIL>"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_SUBJECT_PREFIX = "[CHMVH Website] "

if os.getenv("CHMVH_EMAIL_USER"):
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    EMAIL_HOST = "smtp.sendgrid.net"
    EMAIL_HOST_USER = os.getenv("CHMVH_EMAIL_USER")
    EMAIL_HOST_PASSWORD = os.getenv("CHMVH_EMAIL_PASSWORD")
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True

if os.getenv("CHMVH_ADMIN_NAME"):
    ADMINS = ((os.getenv("CHMVH_ADMIN_NAME"), os.getenv("CHMVH_ADMIN_EMAIL")),)

# Google Analytics
GOOGLE_ANALYTICS_ID = os.getenv("CHMVH_GOOGLE_ANALYTICS_ID")

# ReCAPTCHA
if os.getenv("CHMVH_RECAPTCHA_PRIVATE_KEY"):
    RECAPTCHA_PRIVATE_KEY = os.getenv("CHMVH_RECAPTCHA_PRIVATE_KEY")
    RECAPTCHA_PUBLIC_KEY = os.getenv("CHMVH_RECAPTCHA_PUBLIC_KEY")
else:
    NOCAPTCHA = True
    SILENCED_SYSTEM_CHECKS.append("captcha.recaptcha_test_key_error")


# Gallery Settings
GALLERY_THUMBNAIL_SIZE = 300, 300


# Django Storages

AWS_S3_ENDPOINT_URL = os.getenv('CHMVH_S3_ENDPOINT_URL')
AWS_S3_REGION_NAME = os.getenv('CHMVH_S3_REGION_NAME')

S3_MEDIA_BUCKET = os.getenv('CHMVH_S3_MEDIA_BUCKET')
S3_STATIC_BUCKET = os.getenv('CHMVH_S3_STATIC_BUCKET')

if S3_MEDIA_BUCKET:
    DEFAULT_FILE_STORAGE = 'custom_storage.s3.MediaStorage'

if S3_STATIC_BUCKET:
    STATICFILES_STORAGE = 'custom_storage.s3.StaticStorage'


# Config for django-sass-processor

COMPRESS_ROOT = os.getenv("CHMVH_COMPRESS_ROOT")
SASS_PROCESSOR_STORAGE = 'django.core.files.storage.FileSystemStorage'
SASS_PROCESSOR_STORAGE_OPTIONS = {
    'location': STATIC_ROOT,
    'base_url': STATIC_URL
}
SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, "static")


# Config for djangorestframework

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
    ),
}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",  # noqa
            "datefmt": "%d/%b/%Y %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "standard",
        },
        "mail_admins": {
            "level": "ERROR",
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    "loggers": {
        "root": {
            "handlers": ["console", "mail_admins"],
            "level": logging.INFO,
        }
    },
}

"""
Django settings for chmvh_website project.

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

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

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


def env_bool(name: str) -> bool:
    raw_value = os.getenv(name, "")

    return raw_value.lower() == "true"


def env_list(name: str) -> list[str]:
    raw_value = os.getenv(name, "")

    if not raw_value:
        return []

    return raw_value.split(",")


SILENCED_SYSTEM_CHECKS = []


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


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

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env_bool("CHMVH_DEBUG")

SECRET_KEY = os.getenv("CHMVH_SECRET_KEY")
if DEBUG and not SECRET_KEY:
    SECRET_KEY = "debug"

ALLOWED_HOSTS = env_list("CHMVH_ALLOWED_HOSTS")


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.messages",
    "django.contrib.sessions",
    "django.contrib.sitemaps",
    "django.contrib.staticfiles",
    # Third Party Apps
    "adminsortable2",
    "captcha",
    "rest_framework",
    "sass_processor",
    "solo",
    # Custom Apps
    "common",
    "configuration",
    "contact",
    "gallery",
    "resources",
    "staticpages",
    "team",
]

MIDDLEWARE = [
    "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 = "chmvh_website.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",
                "common.context_processors.analytics",
                "configuration.context_processors.practice_info",
            ],
        },
    },
]

WSGI_APPLICATION = "chmvh_website.wsgi.application"


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql_psycopg2",
        "HOST": os.getenv("CHMVH_DB_HOST", "localhost"),
        "PORT": os.getenv("CHMVH_DB_PORT", "5432"),
        "USER": os.getenv("CHMVH_DB_USER", "postgres"),
        "PASSWORD": os.getenv("CHMVH_DB_PASSWORD"),
        "NAME": os.getenv("CHMVH_DB_NAME", "postgres"),
    }
}

if os.getenv("CHMVH_TEST"):
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": ":memory:",
        }
    }


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

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",  # noqa
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",  # noqa
    },
]


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

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_ROOT = os.getenv('CHMVH_STATIC_ROOT')
STATIC_URL = "/static/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "sass_processor.finders.CssFinder",
]

# Media Files (User Uploaded)

# This is only used for development when we're not uploading files to S3.
MEDIA_ROOT = os.getenv("CHMVH_MEDIA_ROOT", os.path.join(BASE_DIR, "media"))
MEDIA_URL = "/media/"

# HTTPS
if env_bool("CHMVH_HTTPS"):
    CSRF_COOKIE_HTTPONLY = True
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True

    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_SSL_REDIRECT = True
    X_FRAME_OPTIONS = "DENY"


# Email Settings
DEFAULT_FROM_EMAIL = "<EMAIL>"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_SUBJECT_PREFIX = "[CHMVH Website] "

if os.getenv("CHMVH_EMAIL_USER"):
    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    EMAIL_HOST = "smtp.sendgrid.net"
    EMAIL_HOST_USER = os.getenv("CHMVH_EMAIL_USER")
    EMAIL_HOST_PASSWORD = os.getenv("CHMVH_EMAIL_PASSWORD")
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True

if os.getenv("CHMVH_ADMIN_NAME"):
    ADMINS = ((os.getenv("CHMVH_ADMIN_NAME"), os.getenv("CHMVH_ADMIN_EMAIL")),)

# Google Analytics
GOOGLE_ANALYTICS_ID = os.getenv("CHMVH_GOOGLE_ANALYTICS_ID")

# ReCAPTCHA
if os.getenv("CHMVH_RECAPTCHA_PRIVATE_KEY"):
    RECAPTCHA_PRIVATE_KEY = os.getenv("CHMVH_RECAPTCHA_PRIVATE_KEY")
    RECAPTCHA_PUBLIC_KEY = os.getenv("CHMVH_RECAPTCHA_PUBLIC_KEY")
else:
    NOCAPTCHA = True
    SILENCED_SYSTEM_CHECKS.append("captcha.recaptcha_test_key_error")


# Gallery Settings
GALLERY_THUMBNAIL_SIZE = 300, 300


# Django Storages

AWS_S3_ENDPOINT_URL = os.getenv('CHMVH_S3_ENDPOINT_URL')
AWS_S3_REGION_NAME = os.getenv('CHMVH_S3_REGION_NAME')

S3_MEDIA_BUCKET = os.getenv('CHMVH_S3_MEDIA_BUCKET')
S3_STATIC_BUCKET = os.getenv('CHMVH_S3_STATIC_BUCKET')

if S3_MEDIA_BUCKET:
    DEFAULT_FILE_STORAGE = 'custom_storage.s3.MediaStorage'

if S3_STATIC_BUCKET:
    STATICFILES_STORAGE = 'custom_storage.s3.StaticStorage'


# Config for django-sass-processor

COMPRESS_ROOT = os.getenv("CHMVH_COMPRESS_ROOT")
SASS_PROCESSOR_STORAGE = 'django.core.files.storage.FileSystemStorage'
SASS_PROCESSOR_STORAGE_OPTIONS = {
    'location': STATIC_ROOT,
    'base_url': STATIC_URL
}
SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, "static")


# Config for djangorestframework

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.BasicAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": (
        "rest_framework.permissions.IsAuthenticated",
    ),
}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",  # noqa
            "datefmt": "%d/%b/%Y %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "standard",
        },
        "mail_admins": {
            "level": "ERROR",
            "class": "django.utils.log.AdminEmailHandler",
        },
    },
    "loggers": {
        "root": {
            "handlers": ["console", "mail_admins"],
            "level": logging.INFO,
        }
    },
}
Django settings for chmvh_website project.  Generated by 'django-admin startproject' using Django 1.10.1.  For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/  For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! # Application definition # Third Party Apps # Custom Apps # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators # noqa # noqa # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ # Media Files (User Uploaded) # This is only used for development when we're not uploading files to S3. # HTTPS # Email Settings # Google Analytics # ReCAPTCHA # Gallery Settings # Django Storages # Config for django-sass-processor # Config for djangorestframework # noqa