"""
Django settings for restfulshop project.

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

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

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

# 将apps和other_apps通过Pycharm设置为 Mark Source Root，可以实现将这两个包作为根搜索路径，当程序启动的时候，会去项目的根目录搜索，如果根目录中没有，去apps中搜索，所以可以在引入app的时候，直接写 "users.urls"。但是这只是Pycharm这个工具的行为，一旦使用cmd来启动这个项目，脱离了pycharm环境，那么项目就启动失败，cmd不识别Pycharm设置。所以，我们需要在settings.py中，将这两个包分别注册到根搜索目录，这样不管在哪一个环境下面，都可以正确启动项目。
import sys
# sys.path的作用就是向本地项目的搜索路径中添加apps和other_apps。
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'other_apps'))


# 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 = 'g!6$e!dto@y$xqa=akc8u$h!pb9e6cd1&vjj_-jfdtv&s*!m3^'

# 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',
    'corsheaders',
    'users.apps.UsersConfig',
    'goods.apps.GoodsConfig',
    'trades.apps.TradesConfig',
    'xadmin',
    'crispy_forms',
    'rest_framework',
    'django_filters', # 就是drf框架支持的一个第三方的过滤库。
    'rest_framework.authtoken' # 使用drf内置的TokenAuthentication类
]
AUTH_USER_MODEL = 'users.UserInfo'

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',
]
CORS_ORIGIN_ALLOW_ALL = True
ROOT_URLCONF = 'restfulshop.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 = 'restfulshop.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'restshop',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
    }
}

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 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',
    },
]


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

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


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

STATIC_URL = '/static/'
REST_FRAMEWORK = {
    # 这两个配置结合起来才能实现某一个接口对于用户的登录状态进行区分：登录用户可以访问，没有登录用户不能访问。
    "DEFAULT_PERMISSION_CLASSES": (
        'rest_framework.permissions.IsAuthenticated',
    ),
    "DEFAULT_AUTHENTICATION_CLASSES": (
        # TokenAuthentication主要就是检测请求头中是否有正确的Token，从而判断用户是否登录了。
        # 'rest_framework.authentication.TokenAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    )
}

# JWT认证方式：
# 1. 有过期时间，token过期之后，需要用户重新登录，生成新的token；
# 2. Token的这种验证方式需要频繁的访问数据库，需要将前端传递的Token和数据库中的Key进行对比；但是JWT的认证不需要频繁的查询数据库；
import datetime
JWT_AUTH = {
    # 后台的JWT生成的token默认过期时间是5分钟，但是前端将这个token保存到cookie的时候，默认是7天。所以需要将前后端这个token的过期时间保持一致。
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
}

# 使用JSONWebTokenAuthentication和TokenAuthentication进行用户的登录认证，默认都是在对username和password进行验证是否正确，但是如果网站需要使用手机号或者邮箱进行登录，需要重写authenticate()函数
AUTHENTICATION_BACKENDS = (
    'users.views.CustomAuthenticate',
)

# 配置云片网的APIKEY
API_KEY = '70e18bcb007e47b889c97ba1b652b78d'

# 配置项目中用到的支付宝公钥和应用私钥
app_private_key_path = os.path.join(BASE_DIR, 'apps/trades/keys/app_private_rsa_2048.txt')
alipay_public_key_path = os.path.join(BASE_DIR, 'apps/trades/keys/alipay_public_rsa_2048.txt')

