settings.py 6.75 KB
Newer Older
Jon Yu's avatar
Jon Yu committed
1
"""
2
Django settings for {{ project_name }} project.
Jon Yu's avatar
Jon Yu committed
3
4
5
6
7
8
9
10
11
12
13

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

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

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

import os
Jon Yu's avatar
Jon Yu committed
14
import dj_database_url
Jon Yu's avatar
Jon Yu committed
15

Jon Yu's avatar
Jon Yu committed
16

Jon Yu's avatar
Jon Yu committed
17
18
19
20
def str_to_bool(val):
    return val.lower() in ('yes', 'true', 'on', '1')


Jon Yu's avatar
Jon Yu committed
21
22
23
24
25
26
27
28
# 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/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
29
SECRET_KEY = os.getenv('SECRET_KEY')
Jon Yu's avatar
Jon Yu committed
30
31

# SECURITY WARNING: don't run with debug turned on in production!
Jon Yu's avatar
Jon Yu committed
32
DEBUG = str_to_bool(os.getenv('DEBUG', 'off'))
Jon Yu's avatar
Jon Yu committed
33

34
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '127.0.0.1').split(',')
Jon Yu's avatar
Jon Yu committed
35

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# https://docs.djangoproject.com/en/2.2/ref/settings/#admins
# e.g. ADMINS=admin=admin@umich.edu,user=user@umich.edu
#   => [('admin', 'admin@umich.edu'), ('user', 'user@umich.edu')]
ADMINS = [tuple(a.split('=')) for a in os.getenv('ADMINS').split(',')] if os.getenv('ADMINS') else []


# Email
# https://docs.djangoproject.com/en/3.0/topics/email/

if os.getenv('SERVER_EMAIL'):
    SERVER_EMAIL = os.getenv('SERVER_EMAIL')

EMAIL_HOST = os.getenv('EMAIL_HOST', None)

EMAIL_SUBJECT_PREFIX = f'[{os.getenv("EMAIL_SUBJECT_PREFIX", "localhost")}] '

Jon Yu's avatar
Jon Yu committed
52
53
54

# Application definition

55
56
# Add additional non-Django apps here for consistent logging behavior
EXTRA_APPS = [
Jon Yu's avatar
Jon Yu committed
57
    'um_template_ui',
Jon Yu's avatar
Jon Yu committed
58
    'oidc_auth',
59
60
]

Jon Yu's avatar
Jon Yu committed
61
INSTALLED_APPS = [
62
    *EXTRA_APPS,
Jon Yu's avatar
Jon Yu committed
63
64
65
66
67
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
68
    'django.contrib.staticfiles'
69
]
Jon Yu's avatar
Jon Yu committed
70
71
72
73
74
75
76
77
78
79

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',
Jon Yu's avatar
Jon Yu committed
80
    'mozilla_django_oidc.middleware.SessionRefresh'
Jon Yu's avatar
Jon Yu committed
81
82
]

83
ROOT_URLCONF = '{{ project_name }}.urls'
Jon Yu's avatar
Jon Yu committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

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

101
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'
Jon Yu's avatar
Jon Yu committed
102

Jon Yu's avatar
Jon Yu committed
103

Jon Yu's avatar
Jon Yu committed
104
105
106
107
# Authentication

AUTH_USER_MODEL = 'oidc_auth.User'

Jon Yu's avatar
Jon Yu committed
108
AUTHENTICATION_BACKENDS = [
Jon Yu's avatar
Jon Yu committed
109
    'django.contrib.auth.backends.ModelBackend',
Jon Yu's avatar
Jon Yu committed
110
111
]

Jon Yu's avatar
Jon Yu committed
112
113
114
115
116
117
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

if DEBUG is True:
    LOGIN_URL = '/admin'

Jon Yu's avatar
Jon Yu committed
118

Jon Yu's avatar
Jon Yu committed
119
120
121
122
123
124
125
126
127
128
# Mozilla OIDC
# https://mozilla-django-oidc.readthedocs.io/en/stable/

OIDC_RP_CLIENT_ID = os.getenv('OIDC_RP_CLIENT_ID')
OIDC_RP_CLIENT_SECRET = os.getenv('OIDC_RP_CLIENT_SECRET')
OIDC_OP_AUTHORIZATION_ENDPOINT = os.getenv('OIDC_OP_AUTHORIZATION_ENDPOINT')
OIDC_OP_TOKEN_ENDPOINT = os.getenv('OIDC_OP_TOKEN_ENDPOINT')
OIDC_OP_USER_ENDPOINT = os.getenv('OIDC_OP_USER_ENDPOINT')
OIDC_RP_SIGN_ALGO = os.getenv('OIDC_RP_SIGN_ALGO', 'RS256')
OIDC_OP_JWKS_ENDPOINT = os.getenv('OIDC_OP_JWKS_ENDPOINT')
129
OIDC_USERNAME_ALGO = 'oidc_auth.auth.generate_username'
Jon Yu's avatar
Jon Yu committed
130
131
132
133
134
135
136
137
138
139
140
141
OIDC_RP_SCOPES = 'openid email profile'
OIDC_CREATE_USER = str_to_bool(os.getenv('OIDC_CREATE_USER', 'on'))

if (OIDC_RP_CLIENT_ID and OIDC_RP_CLIENT_SECRET and OIDC_OP_AUTHORIZATION_ENDPOINT
        and OIDC_OP_TOKEN_ENDPOINT and OIDC_OP_USER_ENDPOINT):
    EXTRA_APPS += ['mozilla_django_oidc']
    AUTHENTICATION_BACKENDS += ['oidc_auth.auth.UMichOIDCBackend']
    LOGIN_URL = '/oidc/authenticate/'
else:
    print('Skipping OIDCAuthenticationBackend as OIDC variables were not set.')


142
143
144
145
# Work around OpenShift TLS Termination
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')


Jon Yu's avatar
Jon Yu committed
146
147
148
149
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
Jon Yu's avatar
Jon Yu committed
150
    'default': dj_database_url.config(default='sqlite:///db.sqlite3')
Jon Yu's avatar
Jon Yu committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
}


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


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Detroit'

USE_I18N = True

USE_L10N = True

USE_TZ = True


187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# Logging
# https://docs.djangoproject.com/en/2.2/topics/logging/

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
            'style': '{'
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{'
        }
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'formatter': 'simple',
            'filters': ['require_debug_false']
        }
    },
    'loggers': {
        **{
            'django': {
                'level': os.getenv('LOGGING_LEVEL', 'INFO'),
                'handlers': ['console', 'mail_admins'],
                'propagate': True
            },
        },
        **{
            app: {
                'level': os.getenv('LOGGING_LEVEL', 'INFO'),
                'handlers': ['console', 'mail_admins'],
                'propagate': False
            } for app in EXTRA_APPS
        }
    }
}


Jon Yu's avatar
Jon Yu committed
240
241
242
243
244
245
246
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'