-
Notifications
You must be signed in to change notification settings - Fork 1
/
default_settings.py
377 lines (320 loc) · 12.1 KB
/
default_settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import os
import requests
from dotenv import load_dotenv
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import gettext_lazy as _
load_dotenv()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = 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!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Only for windows dev mode without docker
if os.name == 'nt' and os.environ.get('DEBUG'):
DEBUG = True
GDAL_LIBRARY_PATH = 'C:/OSGeo4W/bin/gdal302'
GEOS_LIBRARY_PATH = 'C:/OSGeo4W/bin/geos_c'
ALLOWED_HOSTS = os.environ["ALLOWED_HOST"].split(",")
EMAIL_HOST = os.environ.get('EMAIL_HOST', 'localhost')
EMAIL_PORT = os.environ.get('EMAIL_PORT', 1025)
# Setting to test email sending in console
EMAIL_BACKEND = os.environ.get('EMAIL_BACKEND', 'django.core.mail.backends.console.EmailBackend')
#
DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'DEFAUL_FROM_EMAIL@example.com')
ADMIN_EMAIL_LIST = os.environ.get('ADMIN_EMAIL_LIST', 'ADMIN_EMAIL_LIST@example.com')
REPLY_TO_EMAIL = os.environ.get('REPLY_TO_EMAIL', 'REPLY_TO_EMAIL@example.ch')
# Application definition
INSTALLED_APPS = [
'api.apps.ApiConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'djmoney',
'allauth',
'allauth.account',
'rest_framework',
'rest_framework_gis',
'rest_framework_simplejwt',
'drf_spectacular',
'corsheaders',
'health_check',
'health_check.db',
'health_check.contrib.migrations',
'django_extended_ol',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'allauth.account.middleware.AccountMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['api/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'oidc.status',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wsgi.application'
# 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 = os.getenv('DEFAULT_LANGUAGE', 'en')
DEFAULT_CURRENCY = 'CHF'
LOCALE_PATHS = [
'./api/locale',
'./locale',
]
LANGUAGES = (
('de', _('German')),
('it', _('Italian')),
('fr', _('French')),
('en', _('English')),
('rm', _('Romansh')),
)
TIME_ZONE = 'Europe/Zurich'
DATE_FORMAT = '%d.%m.%Y'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 2
VAT = 0.081
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': os.environ["PGDATABASE"],
'USER': os.environ["PGUSER"],
'HOST': os.environ["PGHOST"],
'PORT': os.environ["PGPORT"],
'PASSWORD': os.environ["PGPASSWORD"],
'OPTIONS': {
'options': '-c search_path=' + os.environ["PGSCHEMA"] + ',public'
},
}
}
# Special needs for geoshop running on PostgreSQL
SPECIAL_DATABASE_CONFIG = {
# A search config with this name must exist on your database, please refer to
# https://www.postgresql.org/docs/current/textsearch-intro.html#TEXTSEARCH-INTRO-CONFIGURATIONS
'FTS_SEARCH_CONFIG': LANGUAGE_CODE
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '{levelname} {module} {filename} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': os.getenv('LOGGING_LEVEL', 'ERROR'),
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('LOGGING_LEVEL', 'ERROR'),
'propagate': False,
},
# uncomment this for DB logging
#'django.db.backends': {
# 'level': 'DEBUG',
# 'handlers': ['console'],
#}
},
}
# Django REST specific configuration
# https://www.django-rest-framework.org/
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 100,
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
SPECTACULAR_SETTINGS = {
'TITLE': 'geoshop API',
'DESCRIPTION': 'API for the geoshop',
'VERSION': '0.1.0',
'SERVE_INCLUDE_SCHEMA': False,
# OTHER SETTINGS
}
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
FORCE_SCRIPT_NAME = os.environ.get('FORCE_SCRIPT_NAME', '')
ROOTURL=os.getenv('ROOTURL', '')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
# For large admin fields like order with order items
DATA_UPLOAD_MAX_NUMBER_FIELDS = 5000
STATIC_URL = FORCE_SCRIPT_NAME + ROOTURL + '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.environ.get('MEDIA_ROOT', os.path.join(BASE_DIR, 'files'))
MEDIA_URL = os.environ.get('MEDIA_URL', FORCE_SCRIPT_NAME + ROOTURL +'/files/')
FRONT_PROTOCOL = os.environ["FRONT_PROTOCOL"]
FRONT_URL = os.environ["FRONT_URL"]
FRONT_HREF = os.environ.get("FRONT_HREF", '')
CSRF_COOKIE_DOMAIN = os.environ["CSRF_COOKIE_DOMAIN"]
CSRF_TRUSTED_ORIGINS = []
for host in ALLOWED_HOSTS:
CSRF_TRUSTED_ORIGINS.append(f'http://{host}')
CSRF_TRUSTED_ORIGINS.append(f'https://{host}')
CORS_ORIGIN_WHITELIST = [
os.environ["FRONT_PROTOCOL"] + '://' + os.environ["FRONT_URL"],
]
DEFAULT_PRODUCT_THUMBNAIL_URL = 'default_product_thumbnail.png'
DEFAULT_METADATA_IMAGE_URL = 'default_metadata_image.png'
AUTO_LEGEND_URL = os.environ.get('AUTO_LEGEND_URL', '')
INTRA_LEGEND_URL = os.environ.get('INTRA_LEGEND_URL', '')
# Geometries settings
# FIXME: Does this work with another SRID?
DEFAULT_SRID = int(os.environ.get('DEFAULT_SRID', '2056'))
# default extent is set to the BBOX of switzerland
DEFAULT_EXTENT = (2828694.200665463,1075126.8548189853,2484749.5514877755,1299777.3195268118)
# Controls values of metadata accessibility field that will turn the metadata public
METADATA_PUBLIC_ACCESSIBILITIES = ['PUBLIC', 'APPROVAL_NEEDED']
# Healthcheck subsets configuration
HEALTH_CHECK = {
"SUBSETS": {
"startup": ["MigrationsHealthCheck", "DatabaseBackend"],
"readiness": ["DatabaseBackend"],
"liveness": []
},
}
FEATURE_FLAGS = {
"oidc": os.environ.get("OIDC_ENABLED", "False") == "False",
"registration": os.environ.get("REGISTRATION_ENABLED", "False") == "False",
}
AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend",)
# OIDC configuration
def discover_endpoints(discovery_url: str) -> dict:
"""
Performs OpenID Connect discovery to retrieve the provider configuration.
"""
response = requests.get(discovery_url)
if response.status_code != 200:
raise ValueError("Failed to retrieve provider configuration.")
provider_config = response.json()
# Extract endpoint URLs from provider configuration
return {
"authorization_endpoint": provider_config["authorization_endpoint"],
"token_endpoint": provider_config["token_endpoint"],
"userinfo_endpoint": provider_config["userinfo_endpoint"],
"jwks_uri": provider_config["jwks_uri"],
"introspection_endpoint": provider_config["introspection_endpoint"],
}
def check_oidc() -> bool:
if FEATURE_FLAGS['oidc']:
return False
missing = []
for x in ["OIDC_RP_CLIENT_ID", "ZITADEL_PROJECT", "OIDC_OP_BASE_URL", "OIDC_PRIVATE_KEYFILE"]:
if not os.environ.get(x):
missing.append(x)
if missing:
raise ImproperlyConfigured(f"OIDC is enabled, but missing required parameters {missing}")
return True
if check_oidc():
INSTALLED_APPS.append('mozilla_django_oidc')
MIDDLEWARE.append('mozilla_django_oidc.middleware.SessionRefresh')
AUTHENTICATION_BACKENDS = ('oidc.PermissionBackend',) + AUTHENTICATION_BACKENDS
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] = (
"oidc.PermissionBackend",
) + REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]
OIDC_RP_CLIENT_ID = os.environ.get("OIDC_RP_CLIENT_ID")
ZITADEL_PROJECT = os.environ.get("ZITADEL_PROJECT")
OIDC_RP_CLIENT_SECRET = os.environ.get("OIDC_RP_CLIENT_SECRET")
OIDC_OP_BASE_URL = os.environ.get("OIDC_OP_BASE_URL")
OIDC_PRIVATE_KEYFILE = os.environ.get("OIDC_PRIVATE_KEYFILE")
OIDC_RP_SIGN_ALGO = "RS256"
OIDC_RP_SCOPES = "openid profile email address phone"
OIDC_USE_PKCE = True
discovery_info = discover_endpoints(
OIDC_OP_BASE_URL + "/.well-known/openid-configuration"
)
OIDC_INTROSPECT_URL = discovery_info["introspection_endpoint"]
OIDC_OP_AUTHORIZATION_ENDPOINT = discovery_info["authorization_endpoint"]
OIDC_OP_TOKEN_ENDPOINT = discovery_info["token_endpoint"]
OIDC_OP_USER_ENDPOINT = discovery_info["userinfo_endpoint"]
OIDC_OP_JWKS_ENDPOINT = discovery_info["jwks_uri"]
LOGIN_REDIRECT_URL = os.environ.get("OIDC_REDIRECT_BASE_URL") + "/oidc/callback"
LOGOUT_REDIRECT_URL = os.environ.get("OIDC_REDIRECT_BASE_URL") + "/"
LOGIN_URL = os.environ.get("OIDC_REDIRECT_BASE_URL") + "/oidc/authenticate"
# Customize openlayers widget used in admin interface
OLWIDGET = {
"globals": {
"srid": DEFAULT_SRID,
"extent": [2420000, 130000, 2900000, 1350000],
"resolutions": [
4000, 3750, 3500, 3250, 3000, 2750, 2500, 2250, 2000, 1750, 1500, 1250,
1000, 750, 650, 500, 250, 100, 50, 20, 10, 5, 2.5, 2, 1.5, 1, 0.5
],
},
"wmts": {
"layer_name": 'ch.kantone.cadastralwebmap-farbe',
"style": 'default',
"matrix_set": '2056',
"attributions": '<a target="new" href="https://www.swisstopo.admin.ch/internet/swisstopo/en/home.html"'
+ '>swisstopo</a>', # optional
"url_template": 'https://wmts10.geo.admin.ch/1.0.0/{Layer}/default/current/2056/{TileMatrix}/{TileCol}/{TileRow}.png',
"request_encoding": 'REST', # optional
"format": 'image/png' # optional
}
}