"""
Django settings for app project.

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/

Any setting that is configured via an environment variable may
also be set in a `.env` file in the project base directory.
"""
from os import path

import django_heroku
import dj_database_url
from environs import Env
from furl import furl


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

env = Env()
env.read_env(path.join(BASE_DIR, '.env'), recurse=False)


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY',
                 'v8sk33sy82!uw3ty=!jjv5vp7=s2phrzw(m(hrn^f7e_#1h2al')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DEBUG', True)

# True if you want to allow users to be able to create an account
ALLOW_SIGNUP = env.bool('ALLOW_SIGNUP', True)

# ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'server.apps.ServerConfig',
    'api.apps.ApiConfig',
    'widget_tweaks',
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
    'social_django',
    'polymorphic',
    'webpack_loader',
    'corsheaders',
    'drf_yasg'
]

CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER = env('CLOUD_BROWSER_LIBCLOUD_PROVIDER', None)
CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT = env('CLOUD_BROWSER_LIBCLOUD_ACCOUNT', None)
CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY = env('CLOUD_BROWSER_LIBCLOUD_KEY', None)

if CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER:
    CLOUD_BROWSER_DATASTORE = 'ApacheLibcloud'
    CLOUD_BROWSER_OBJECT_REDIRECT_URL = '/v1/cloud-upload'
    INSTALLED_APPS.append('cloud_browser')

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
    'social_django.middleware.SocialAuthExceptionMiddleware',
    'applicationinsights.django.ApplicationInsightsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [path.join(BASE_DIR, 'server/templates'), path.join(BASE_DIR, 'authentification/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',
                'social_django.context_processors.login_redirect',
            ],
            'libraries': {
                'analytics': 'server.templatetags.analytics',
                'utils_templating': 'authentification.templatetags.utils_templating',
            },
        },
    },
]

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

STATIC_URL = '/static/'
STATIC_ROOT = path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = [
    static_path
    for static_path in (
        path.join(BASE_DIR, 'server', 'static', 'assets'),
        path.join(BASE_DIR, 'server', 'static', 'static'),
    )
    if path.isdir(static_path)
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

WEBPACK_LOADER = {
    'DEFAULT': {
        'CACHE': not DEBUG,
        'BUNDLE_DIR_NAME': 'bundle/',
        'STATS_FILE': path.join(BASE_DIR, 'server', 'static', 'webpack-stats.json'),
        'POLL_INTERVAL': 0.1,
        'TIMEOUT': None,
        'IGNORE': [r'.*\.hot-update.js', r'.+\.map']
    }
}

WSGI_APPLICATION = 'app.wsgi.application'

AUTHENTICATION_BACKENDS = [
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.azuread_tenant.AzureADTenantOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]

HEADER_AUTH_USER_NAME = env('HEADER_AUTH_USER_NAME', '')
HEADER_AUTH_USER_GROUPS = env('HEADER_AUTH_USER_GROUPS', '')
HEADER_AUTH_ADMIN_GROUP_NAME = env('HEADER_AUTH_ADMIN_GROUP_NAME', '')
HEADER_AUTH_GROUPS_SEPERATOR = env('HEADER_AUTH_GROUPS_SEPERATOR', default=',')

if HEADER_AUTH_USER_NAME and HEADER_AUTH_USER_GROUPS and HEADER_AUTH_ADMIN_GROUP_NAME:
    MIDDLEWARE.append('server.middleware.HeaderAuthMiddleware')
    AUTHENTICATION_BACKENDS.append('django.contrib.auth.backends.RemoteUserBackend')

SOCIAL_AUTH_GITHUB_KEY = env('OAUTH_GITHUB_KEY', None)
SOCIAL_AUTH_GITHUB_SECRET = env('OAUTH_GITHUB_SECRET', None)
GITHUB_ADMIN_ORG_NAME = env('GITHUB_ADMIN_ORG_NAME', None)
GITHUB_ADMIN_TEAM_NAME = env('GITHUB_ADMIN_TEAM_NAME', None)

if GITHUB_ADMIN_ORG_NAME and GITHUB_ADMIN_TEAM_NAME:
    SOCIAL_AUTH_GITHUB_SCOPE = ['read:org']

SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = env('OAUTH_AAD_KEY', None)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = env('OAUTH_AAD_SECRET', None)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = env('OAUTH_AAD_TENANT', None)
AZUREAD_ADMIN_GROUP_ID = env('AZUREAD_ADMIN_GROUP_ID', None)

if AZUREAD_ADMIN_GROUP_ID:
    SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_RESOURCE = 'https://graph.microsoft.com/'
    SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SCOPE = ['Directory.Read.All']

SOCIAL_AUTH_PIPELINE = [
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    'server.social_auth.fetch_github_permissions',
    'server.social_auth.fetch_azuread_permissions',
]

ROLE_PROJECT_ADMIN = env('ROLE_PROJECT_ADMIN', 'project_admin')
ROLE_ANNOTATOR = env('ROLE_ANNOTATOR', 'annotator')
ROLE_ANNOTATION_APPROVER = env('ROLE_ANNOTATION_APPROVER', 'annotation_approver')

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': env.int('DOCCANO_PAGE_SIZE', default=5),
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'SEARCH_PARAM': 'q',
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_xml.renderers.XMLRenderer'
    )
}

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
TEST_OUTPUT_DIR = path.join(BASE_DIR, 'junitxml')

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/projects/'
LOGOUT_REDIRECT_URL = '/'

django_heroku.settings(locals(), test_runner=False)

# Change 'default' database configuration with $DATABASE_URL.
DATABASES['default'].update(dj_database_url.config(
    env='DATABASE_URL',
    conn_max_age=env.int('DATABASE_CONN_MAX_AGE', 500),
    ssl_require='sslmode' not in furl(env('DATABASE_URL', '')).args,
))

# work-around for dj-database-url: explicitly disable ssl for sqlite
if DATABASES['default'].get('ENGINE') == 'django.db.backends.sqlite3':
    DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)

# work-around for dj-database-url: patch ssl for mysql
if DATABASES['default'].get('ENGINE') == 'django.db.backends.mysql':
    DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)
    if env('MYSQL_SSL_CA', None):
        DATABASES['default'].setdefault('OPTIONS', {})\
            .setdefault('ssl', {}).setdefault('ca', env('MYSQL_SSL_CA', None))

# default to a sensible modern driver for Azure SQL
if DATABASES['default'].get('ENGINE') == 'sql_server.pyodbc':
    DATABASES['default'].setdefault('OPTIONS', {})\
        .setdefault('driver', 'ODBC Driver 17 for SQL Server')

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', False)
CSRF_COOKIE_SECURE = env.bool('CSRF_COOKIE_SECURE', False)
CSRF_TRUSTED_ORIGINS = env.list('CSRF_TRUSTED_ORIGINS', [])

# Allow all host headers
# ALLOWED_HOSTS = ['*']

# Size of the batch for creating documents
# on the import phase
IMPORT_BATCH_SIZE = env.int('IMPORT_BATCH_SIZE', 500)

GOOGLE_TRACKING_ID = env('GOOGLE_TRACKING_ID', 'UA-125643874-2').strip()

AZURE_APPINSIGHTS_IKEY = env('AZURE_APPINSIGHTS_IKEY', None)
APPLICATION_INSIGHTS = {
    'ikey': AZURE_APPINSIGHTS_IKEY if AZURE_APPINSIGHTS_IKEY else None,
    'endpoint': env('AZURE_APPINSIGHTS_ENDPOINT', None),
}

# necessary for email verification of new accounts
EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', False)
EMAIL_HOST = env('EMAIL_HOST', None)
EMAIL_HOST_USER = env('EMAIL_HOST_USER', None)
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', None)
EMAIL_PORT = env.int('EMAIL_PORT', 587)

if not EMAIL_HOST:
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'


if DEBUG:
    CORS_ORIGIN_WHITELIST = (
        'http://127.0.0.1:3000',
        'http://0.0.0.0:3000',
        'http://localhost:3000'
    )

app/app/settings.py
"""
Django settings for app project.

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/

Any setting that is configured via an environment variable may
also be set in a `.env` file in the project base directory.
"""
from os import path

import django_heroku
import dj_database_url
from environs import Env
from furl import furl


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

env = Env()
env.read_env(path.join(BASE_DIR, '.env'), recurse=False)


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY',
                 'v8sk33sy82!uw3ty=!jjv5vp7=s2phrzw(m(hrn^f7e_#1h2al')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DEBUG', True)

# True if you want to allow users to be able to create an account
ALLOW_SIGNUP = env.bool('ALLOW_SIGNUP', True)

# ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'server.apps.ServerConfig',
    'api.apps.ApiConfig',
    'widget_tweaks',
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
    'social_django',
    'polymorphic',
    'webpack_loader',
    'corsheaders',
    'drf_yasg'
]

CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER = env('CLOUD_BROWSER_LIBCLOUD_PROVIDER', None)
CLOUD_BROWSER_APACHE_LIBCLOUD_ACCOUNT = env('CLOUD_BROWSER_LIBCLOUD_ACCOUNT', None)
CLOUD_BROWSER_APACHE_LIBCLOUD_SECRET_KEY = env('CLOUD_BROWSER_LIBCLOUD_KEY', None)

if CLOUD_BROWSER_APACHE_LIBCLOUD_PROVIDER:
    CLOUD_BROWSER_DATASTORE = 'ApacheLibcloud'
    CLOUD_BROWSER_OBJECT_REDIRECT_URL = '/v1/cloud-upload'
    INSTALLED_APPS.append('cloud_browser')

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
    'social_django.middleware.SocialAuthExceptionMiddleware',
    'applicationinsights.django.ApplicationInsightsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [path.join(BASE_DIR, 'server/templates'), path.join(BASE_DIR, 'authentification/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',
                'social_django.context_processors.login_redirect',
            ],
            'libraries': {
                'analytics': 'server.templatetags.analytics',
                'utils_templating': 'authentification.templatetags.utils_templating',
            },
        },
    },
]

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

STATIC_URL = '/static/'
STATIC_ROOT = path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = [
    static_path
    for static_path in (
        path.join(BASE_DIR, 'server', 'static', 'assets'),
        path.join(BASE_DIR, 'server', 'static', 'static'),
    )
    if path.isdir(static_path)
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

WEBPACK_LOADER = {
    'DEFAULT': {
        'CACHE': not DEBUG,
        'BUNDLE_DIR_NAME': 'bundle/',
        'STATS_FILE': path.join(BASE_DIR, 'server', 'static', 'webpack-stats.json'),
        'POLL_INTERVAL': 0.1,
        'TIMEOUT': None,
        'IGNORE': [r'.*\.hot-update.js', r'.+\.map']
    }
}

WSGI_APPLICATION = 'app.wsgi.application'

AUTHENTICATION_BACKENDS = [
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.azuread_tenant.AzureADTenantOAuth2',
    'django.contrib.auth.backends.ModelBackend',
]

HEADER_AUTH_USER_NAME = env('HEADER_AUTH_USER_NAME', '')
HEADER_AUTH_USER_GROUPS = env('HEADER_AUTH_USER_GROUPS', '')
HEADER_AUTH_ADMIN_GROUP_NAME = env('HEADER_AUTH_ADMIN_GROUP_NAME', '')
HEADER_AUTH_GROUPS_SEPERATOR = env('HEADER_AUTH_GROUPS_SEPERATOR', default=',')

if HEADER_AUTH_USER_NAME and HEADER_AUTH_USER_GROUPS and HEADER_AUTH_ADMIN_GROUP_NAME:
    MIDDLEWARE.append('server.middleware.HeaderAuthMiddleware')
    AUTHENTICATION_BACKENDS.append('django.contrib.auth.backends.RemoteUserBackend')

SOCIAL_AUTH_GITHUB_KEY = env('OAUTH_GITHUB_KEY', None)
SOCIAL_AUTH_GITHUB_SECRET = env('OAUTH_GITHUB_SECRET', None)
GITHUB_ADMIN_ORG_NAME = env('GITHUB_ADMIN_ORG_NAME', None)
GITHUB_ADMIN_TEAM_NAME = env('GITHUB_ADMIN_TEAM_NAME', None)

if GITHUB_ADMIN_ORG_NAME and GITHUB_ADMIN_TEAM_NAME:
    SOCIAL_AUTH_GITHUB_SCOPE = ['read:org']

SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = env('OAUTH_AAD_KEY', None)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = env('OAUTH_AAD_SECRET', None)
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = env('OAUTH_AAD_TENANT', None)
AZUREAD_ADMIN_GROUP_ID = env('AZUREAD_ADMIN_GROUP_ID', None)

if AZUREAD_ADMIN_GROUP_ID:
    SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_RESOURCE = 'https://graph.microsoft.com/'
    SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SCOPE = ['Directory.Read.All']

SOCIAL_AUTH_PIPELINE = [
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    'server.social_auth.fetch_github_permissions',
    'server.social_auth.fetch_azuread_permissions',
]

ROLE_PROJECT_ADMIN = env('ROLE_PROJECT_ADMIN', 'project_admin')
ROLE_ANNOTATOR = env('ROLE_ANNOTATOR', 'annotator')
ROLE_ANNOTATION_APPROVER = env('ROLE_ANNOTATION_APPROVER', 'annotation_approver')

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path.join(BASE_DIR, 'db.sqlite3'),
    }
}


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

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': env.int('DOCCANO_PAGE_SIZE', default=5),
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'SEARCH_PARAM': 'q',
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_xml.renderers.XMLRenderer'
    )
}

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
TEST_OUTPUT_DIR = path.join(BASE_DIR, 'junitxml')

LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/projects/'
LOGOUT_REDIRECT_URL = '/'

django_heroku.settings(locals(), test_runner=False)

# Change 'default' database configuration with $DATABASE_URL.
DATABASES['default'].update(dj_database_url.config(
    env='DATABASE_URL',
    conn_max_age=env.int('DATABASE_CONN_MAX_AGE', 500),
    ssl_require='sslmode' not in furl(env('DATABASE_URL', '')).args,
))

# work-around for dj-database-url: explicitly disable ssl for sqlite
if DATABASES['default'].get('ENGINE') == 'django.db.backends.sqlite3':
    DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)

# work-around for dj-database-url: patch ssl for mysql
if DATABASES['default'].get('ENGINE') == 'django.db.backends.mysql':
    DATABASES['default'].get('OPTIONS', {}).pop('sslmode', None)
    if env('MYSQL_SSL_CA', None):
        DATABASES['default'].setdefault('OPTIONS', {})\
            .setdefault('ssl', {}).setdefault('ca', env('MYSQL_SSL_CA', None))

# default to a sensible modern driver for Azure SQL
if DATABASES['default'].get('ENGINE') == 'sql_server.pyodbc':
    DATABASES['default'].setdefault('OPTIONS', {})\
        .setdefault('driver', 'ODBC Driver 17 for SQL Server')

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = env.bool('SESSION_COOKIE_SECURE', False)
CSRF_COOKIE_SECURE = env.bool('CSRF_COOKIE_SECURE', False)
CSRF_TRUSTED_ORIGINS = env.list('CSRF_TRUSTED_ORIGINS', [])

# Allow all host headers
# ALLOWED_HOSTS = ['*']

# Size of the batch for creating documents
# on the import phase
IMPORT_BATCH_SIZE = env.int('IMPORT_BATCH_SIZE', 500)

GOOGLE_TRACKING_ID = env('GOOGLE_TRACKING_ID', 'UA-125643874-2').strip()

AZURE_APPINSIGHTS_IKEY = env('AZURE_APPINSIGHTS_IKEY', None)
APPLICATION_INSIGHTS = {
    'ikey': AZURE_APPINSIGHTS_IKEY if AZURE_APPINSIGHTS_IKEY else None,
    'endpoint': env('AZURE_APPINSIGHTS_ENDPOINT', None),
}

# necessary for email verification of new accounts
EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', False)
EMAIL_HOST = env('EMAIL_HOST', None)
EMAIL_HOST_USER = env('EMAIL_HOST_USER', None)
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', None)
EMAIL_PORT = env.int('EMAIL_PORT', 587)
DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', 'webmaster@localhost')

if not EMAIL_HOST:
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'


if DEBUG:
    CORS_ORIGIN_WHITELIST = (
        'http://127.0.0.1:3000',
        'http://0.0.0.0:3000',
        'http://localhost:3000'
    )

app/app/settings.py
diff --git a/app/app/settings.py b/app/app/settings.py
index 36233b8d63..cb7303d7b5 100644
--- a/app/app/settings.py
+++ b/app/app/settings.py
@@ -314,6 +314,7 @@
 EMAIL_HOST_USER = env('EMAIL_HOST_USER', None)
 EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', None)
 EMAIL_PORT = env.int('EMAIL_PORT', 587)
+DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL', 'webmaster@localhost')
 
 if not EMAIL_HOST:
     EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
diff --git a/awsdeploy.yml b/awsdeploy.yml
index bc1b0f2508..d1920c949e 100644
--- a/awsdeploy.yml
+++ b/awsdeploy.yml
@@ -75,6 +75,38 @@ Resources:
             - !Ref SecretKey
             - |+
 
+            - sudo tee -a /env.list <<< EMAIL_USE_TLS=
+            - !Ref EMailUseTSL
+            - |+
+
+            - sudo tee -a /env.list <<< EMAIL_HOST=
+            - !Ref EMailHost
+            - |+
+
+            - sudo tee -a /env.list <<< EMAIL_PORT=
+            - !Ref EMailHostPort
+            - |+
+
+            - sudo tee -a /env.list <<< EMAIL_HOST_USER=
+            - !Ref EMailHostUser
+            - |+
+
+            - sudo tee -a /env.list <<< EMAIL_HOST_PASSWORD=
+            - !Ref EMailHostPassword
+            - |+
+
+            - sudo tee -a /env.list <<< WORKERS=
+            - !Ref WorkersCount
+            - |+
+
+            - sudo tee -a /env.list <<< DEFAULT_FROM_EMAIL=
+            - !Ref FromEmail
+            - |+
+
+            - sudo tee -a /env.list <<< DOCKER_IMAGE=
+            - !Ref DockerImageName
+            - |+
+
             - |
               set -a
             - |
@@ -82,12 +114,12 @@ Resources:
             - |
               set +a
             - |
-              sudo docker pull doccano/doccano:latest
+              sudo docker pull ${DOCKER_IMAGE}
             - >
               sudo docker run -d --name doccano --env-file /env.list -p 80:8000
-              doccano/doccano:latest
+              ${DOCKER_IMAGE}
             - >
-              sudo docker exec doccano tools/create-admin.sh ${ADMIN} ${EMAIL}
+              sleep 3 && sudo docker exec doccano tools/create-admin.sh ${ADMIN} ${EMAIL}
               ${PASSWORD}
     Metadata:
       'AWS::CloudFormation::Designer':
@@ -195,6 +227,7 @@ Parameters:
     ConstraintDescription: must be the name of an existing EC2 KeyPair.
   AdminUserName:
     Description: The admin account user name
+    Default: 'admin'
     Type: String
     MinLength: 1
     MaxLength: 16
@@ -224,6 +257,53 @@ Parameters:
     Description: Secret key for Django
     Type: String
     AllowedPattern: '^[a-zA-Z0-9]*$'
+  EMailUseTSL:
+    Default: 'False'
+    AllowedValues:
+      - 'False'
+      - 'True'
+    Description: SMTP will use TSL
+    Type: String
+    AllowedPattern: '^[a-zA-Z0-9]*$'
+  EMailHost:
+    Description: SMTP Host
+    Type: String
+    AllowedPattern: '^[\w-]+(\.[\w-]+)*(\.[a-z]{2,})$'
+  EMailHostUser:
+    Description: SMTP Host User
+    Type: String
+    MinLength: 1
+    MaxLength: 25
+    AllowedPattern: '^[a-zA-Z0-9][a-zA-Z0-9]{1,25}$'
+  EMailHostPassword:
+    Description: SMTP Host User password
+    Type: String
+    NoEcho: true
+    MinLength: 0
+    MaxLength: 60
+    AllowedPattern: '^\p{Graph}+$'
+  EMailHostPort:
+    Description: SMTP Port
+    Type: String
+    MinLength: 1
+    MaxLength: 5
+    AllowedPattern: '^\d+$'
+  WorkersCount:
+    Description: Workers Count
+    Type: String
+    MinLength: 1
+    MaxLength: 3
+    AllowedPattern: '^\d+$'
+  FromEmail:
+    Default: webmaster@localhost
+    Description: The email used to send from singup messages
+    Type: String
+    AllowedPattern: '^[\x20-\x45]?[\w-\+]+(\.[\w]+)*@[\w-]+(\.[\w]+)*(\.[a-z]{2,})?$'
+  DockerImageName:
+    Default: doccano/doccano:latest
+    Description: The Docker image name
+    Type: String
+    AllowedPattern: '^[\w_-]+/[\w_-]+:[\w_-]+$'
 Outputs:
   PublicDNS:
     Value: !GetAtt 

Signup verification email not received
How to reproduce the behaviour
---------
I setup the project using AWS one-click deployment button. Everything works fine, but when a new user sign ups, email verification is not received. I believe I have to set up a email host configurations in `settings.py`. How do I set it up as the project has already been deployed? Is it in the `/env.list` file, or the AWS one-click automatically does this?

```
# necessary for email verification of new accounts
EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', False)
EMAIL_HOST = env('EMAIL_HOST', None)
EMAIL_HOST_USER = env('EMAIL_HOST_USER', None)
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD', None)
EMAIL_PORT = env.int('EMAIL_PORT', 587)
```
Your Environment
---------
<!-- Include details of your environment. -->

*   Operating System: AWS ubuntu
*   Python Version Used: 3.6
*   When you install doccano: Mar 30, 2020
*   How did you install doccano (Heroku button etc): AWS one-click deployment

---------
Also, when I deployed the project using docker-compose by pulling the github project, the project looks older and not as in demo http://doccano.herokuapp.com/. Why is that? Am I missing something here?


