-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsettings.py
More file actions
280 lines (228 loc) · 8.48 KB
/
settings.py
File metadata and controls
280 lines (228 loc) · 8.48 KB
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
"""
Django settings for balancer_backend project.
Generated by 'django-admin startproject' using Django 4.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
import os
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/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 = bool(os.environ.get("DEBUG", default=0))
# Fetching the value from the environment and splitting to list if necessary.
# Fallback to '*' if the environment variable is not set.
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "*").split()
# If the environment variable contains '*', the split method would create a list with an empty string.
# So you need to check for this case and adjust accordingly.
if ALLOWED_HOSTS == ["*"] or ALLOWED_HOSTS == [""]:
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"balancer_backend",
"api",
"corsheaders",
"rest_framework",
"djoser",
'drf_spectacular',
]
MIDDLEWARE = [
"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",
"corsheaders.middleware.CorsMiddleware",
]
ROOT_URLCONF = "balancer_backend.urls"
CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ALLOWED_ORIGINS", "http://localhost:3000").split(",")
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BASE_DIR, "build")],
"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",
],
},
},
]
# Set the login redirect URL after successful email verification
# Change this to your desired URL
LOGIN_REDIRECT_URL = os.environ.get("LOGIN_REDIRECT_URL")
WSGI_APPLICATION = "balancer_backend.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
# Detect connection type based on SQL_HOST
# CloudNativePG: Kubernetes service names (e.g., "balancer-postgres-rw" or contains ".svc.cluster.local")
# AWS RDS: External hostnames (e.g., "balancer-db.xxxxx.us-east-1.rds.amazonaws.com")
SQL_HOST = os.environ.get("SQL_HOST", "localhost")
is_cloudnativepg = (
".svc.cluster.local" in SQL_HOST
or not ("." in SQL_HOST and len(SQL_HOST.split(".")) > 2)
or SQL_HOST.count(".") <= 1
)
# Build database configuration
db_config = {
"ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
"NAME": os.environ.get("SQL_DATABASE", BASE_DIR / "db.sqlite3"),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": SQL_HOST,
"PORT": os.environ.get("SQL_PORT", "5432"),
}
# Configure SSL/TLS based on connection type
# CloudNativePG within cluster typically doesn't require SSL
# AWS RDS typically requires SSL
if db_config["ENGINE"] == "django.db.backends.postgresql":
# Check if SSL is explicitly configured
ssl_mode = os.environ.get("SQL_SSL_MODE", None)
if ssl_mode:
# Use explicit SSL configuration
db_config["OPTIONS"] = {
"sslmode": ssl_mode,
}
elif not is_cloudnativepg:
# For external databases (AWS RDS), default to require SSL
# This can be overridden by setting SQL_SSL_MODE
db_config["OPTIONS"] = {
"sslmode": "require",
}
# For CloudNativePG (within cluster), no SSL by default
DATABASES = {
"default": db_config,
}
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_TLS = True
# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = "/static/"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "build/static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "static")
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
]
REST_FRAMEWORK = {
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"],
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
SPECTACULAR_SETTINGS = {
'TITLE': 'Balancer API',
'DESCRIPTION': 'API for the Balancer medication decision support tool',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
'SECURITY': [{'jwtAuth': []}],
'SWAGGER_UI_SETTINGS': {
'persistAuthorization': True,
},
}
SIMPLE_JWT = {
"AUTH_HEADER_TYPES": ("JWT",),
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
"TOKEN_OBTAIN_SERIALIZER": "api.models.TokenObtainPairSerializer.MyTokenObtainPairSerializer",
"AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
}
DJOSER = {
"LOGIN_FIELD": "email",
"USER_CREATE_PASSWORD_RETYPE": True,
"USERNAME_CHANGED_EMAIL_CONFIRMATION": True,
"PASSWORD_CHANGED_EMAIL_CONFIRMATION": True,
"SEND_CONFIRMATION_EMAIL": True,
"SET_USERNAME_RETYPE": True,
"SET_PASSWORD_RETYPE": True,
"PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}",
"USERNAME_RESET_CONFIRM_URL": "email/reset/confirm/{uid}/{token}",
"ACTIVATION_URL": "activate/{uid}/{token}",
"SEND_ACTIVATION_EMAIL": True,
"SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy",
"SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": [
"http://localhost:8000/google",
"http://localhost:8000/facebook",
],
"SERIALIZERS": {
"user_create": "api.models.serializers.UserCreateSerializer",
"user": "api.models.serializers.UserCreateSerializer",
"current_user": "api.models.serializers.UserCreateSerializer",
"user_delete": "djoser.serializers.UserDeleteSerializer",
},
}
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTH_USER_MODEL = "api.UserAccount"
# Logging configuration
# LOGGING = {
# "version": 1,
# "disable_existing_loggers": False,
# "formatters": {
# "verbose": {
# "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}",
# "style": "{",
# },
# "simple": {
# "format": "{levelname} {message}",
# "style": "{",
# },
# },
# "handlers": {
# "console": {
# "class": "logging.StreamHandler",
# "formatter": "verbose",
# },
# },
# "root": {
# "handlers": ["console"],
# "level": "INFO",
# },
# }