"""
Django settings for mcs3 project.

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

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

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

import os

# 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/ja/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# 置き換え済み
SECRET_KEY = 'x%040#bx#azj(4lvhle)y2i8^adzs2a%avjcs#+y@1y9u+cgy('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',  # ドメインの設定
    'django.contrib.sitemaps',  # サイトマップの作成
    'sass_processor',  # SASSを処理
    'imagekit',  # アップロードされた画像の処理
    'django_cleanup.apps.CleanupConfig',  # 削除された画像の処理
    'markdownx',  # Markdownを処理
    'django_bleach',  # XSS対策
    "compressor",  # JS, CSSの圧縮
    'main.apps.MainConfig',  # メインアプリの設定
    'debug_toolbar',  # 製作支援ツール
    'axes',  # ログインページのセキュリティ強化
]

SITE_ID = 1

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'htmlmin.middleware.HtmlMinifyMiddleware',  # HTMLの圧縮
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'htmlmin.middleware.MarkRequestMiddleware',  # HTMLの圧縮
    'debug_toolbar.middleware.DebugToolbarMiddleware',  # 製作支援ツール
    'axes.middleware.AxesMiddleware',  # ログインページのセキュリティ強化
]

ROOT_URLCONF = 'mcs3.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mcs3.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'hoge',
        'USER': 'hoge',
        'PASSWORD': 'hoge',
        'HOST': 'postgres',  # mcs3-postgresコンテナに接続
        'PORT': '',
    }
}


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


# Customizing authentication
# https://docs.djangoproject.com/ja/2.2/topics/auth/customizing/

AUTHENTICATION_BACKENDS = [
    'axes.backends.AxesBackend',  # ログインページのセキュリティ強化
    'django.contrib.auth.backends.ModelBackend',
]


# Internationalization
# https://docs.djangoproject.com/ja/2.1/topics/i18n/

LANGUAGE_CODE = 'ja-jp'
TIME_ZONE = 'Asia/Tokyo'  # データは変更されるが，HTTPヘッダは変更されない（nginxのせい）
USE_I18N = True
USE_L10N = True
USE_TZ = True


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

STATIC_URL = '/static/'
STATIC_ROOT = '/static'  # `./manage.py collectstatic`を実行でnginxと共有
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',  # 圧縮
)


# Media files (アップロードされた画像を保存するディレクトリ)

MEDIA_URL =  '/media/'
MEDIA_ROOT = '/media'


# Cache Setting
# https://docs.djangoproject.com/ja/2.1/topics/cache/
# デバッグモードのときにキャッシュを無効化します．

if not DEBUG:
    CACHES = {
        'default' : {
            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            'LOCATION': 'memcached:11211',
        }
    }
# django-axesを使用する場合，DummyCache，LocMemCache，FileBasedCacheは使用することができません．


# Security Settings
# https://docs.djangoproject.com/en/2.2/topics/security/

if DEBUG:
    SECURE_HSTS_SECONDS = 365 * 24 * 60 * 60  # HSTSを使用して365日間HTTPSでの通信を強制
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True  # HSTSの設定をサブドメインにも適用
    SECURE_HSTS_PRELOAD = True  # プリロードHSTSを有効化
SECURE_SSL_REDIRECT = True  # 常時SSLを有効化
SESSION_COOKIE_SECURE = True  # CookieのSecureを有効化
SESSION_COOKIE_AGE = 24 * 60 * 60  # セッションは1日まで有効
CSRF_COOKIE_SECURE = True  # CSRF CookieのSecureを有効化
SECURE_CONTENT_TYPE_NOSNIFF = True  # ファイルの内容をサーバ側で指定
SECURE_BROWSER_XSS_FILTER = True  # クライアント側のXSS対策を有効化
X_FRAME_OPTIONS = 'DENY'  # iframeで他のサイトを埋め込まない


# django axes
# https://django-axes.readthedocs.io/en/latest/index.html

AXES_FAILURE_LIMIT = 5  # ログインに失敗できる回数
# Caddy Web Server テスト用
# AXES_META_PRECEDENCE_ORDER = (
#     'HTTP_X_FORWARDED_FOR',
# )


# Debug Toolbar
# https://django-debug-toolbar.readthedocs.io/en/latest/
# Dockerの場合，自動で切り替えができない(?)

import socket
import os

# IPアドレスの自動登録
if DEBUG:
    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[:-1] + '1' for ip in ips] + ['127.0.0.1', '10.0.2.2']


# SASS Processor Settings
# https://github.com/jrief/django-sass-processor

SASS_PROCESSOR_ROOT = STATIC_ROOT
SASS_PROCESSOR_INCLUDE_FILE_PATTERN = r'^.+\.(sass|scss)$'
SASS_PRECISION = 5
SASS_OUTPUT_STYLE = 'compressed'
SASS_TEMPLATE_EXTS = ['.html', '.haml']


# MarkdownX Settings
# https://neutronx.github.io/django-markdownx/

MARKDOWNX_MARKDOWN_EXTENSIONS = [
    'markdown.extensions.tables',
    'markdown.extensions.fenced_code',
    'markdown.extensions.nl2br'
]
# MarkdownX内に画像がドラッグアンドドロップされたときの処理（できればしてほしくない…）
MARKDOWNX_IMAGE_MAX_SIZE = {
    'size': (600, 600),
    'quality': 75
}


# Bleach Settings
# https://django-bleach.readthedocs.io/en/latest/

BLEACH_ALLOWED_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'b', 'i', 'u', 'em',  'strong', 'del', 'mark', 'a', 'ul', 'ol', 'li', 'blockquote', 'code', 'pre', 'hr', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'img']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'src', 'alt', 'style']
BLEACH_ALLOWED_STYLES = ['font-family', 'font-weight', 'text-decoration', 'font-size', 'font-variant', 'color', 'line-height', 'letter-spacing', 'margin', 'padding', 'text-indent', 'text-align', 'text-shadow', 'filter']
BLEACH_STRIP_TAGS = True


# Htmlmin Settings
# https://github.com/cobrateam/django-htmlmin

EXCLUDE_FROM_MINIFYING = (
    '^admin/',
)


# Compressor Settings
# https://django-compressor.readthedocs.io/en/stable/

COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter','compressor.filters.cssmin.rCSSMinFilter']
# COMPRESS_ENABLED = True
