Skip to content

Commit 41d34ab

Browse files
Refactor: CORS settings and improve domain extraction logic
1 parent 7d2664e commit 41d34ab

File tree

1 file changed

+33
-18
lines changed

1 file changed

+33
-18
lines changed

backend/aiproject/settings.py

+33-18
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import logging
1414
import os
1515
from socket import gethostbyname, gethostname
16+
from urllib.parse import urlparse
1617

1718
import dj_database_url
1819
import environ
@@ -42,9 +43,6 @@
4243
default="https://api-prod.raw-data.hotosm.org/v1",
4344
)
4445

45-
CORS_ALLOW_HEADERS = list(default_headers) + [
46-
"access-token",
47-
]
4846
if env("GDAL_LIBRARY_PATH", default=False):
4947
GDAL_LIBRARY_PATH = env("GDAL_LIBRARY_PATH")
5048

@@ -120,21 +118,7 @@
120118
"django.contrib.messages.middleware.MessageMiddleware",
121119
"django.middleware.clickjacking.XFrameOptionsMiddleware",
122120
]
123-
ALLOWED_ORIGINS = env("CORS_ALLOWED_ORIGINS", default="http://127.0.0.1:8000").split(
124-
","
125-
)
126-
127-
CORS_ORIGIN_WHITELIST = ALLOWED_ORIGINS
128-
129-
ALLOWED_HOSTS = [
130-
"localhost",
131-
"127.0.0.1",
132-
HOSTNAME,
133-
gethostbyname(gethostname()),
134-
] + ALLOWED_ORIGINS
135-
136121

137-
CORS_ORIGIN_ALLOW_ALL = env("CORS_ORIGIN_ALLOW_ALL", default=False)
138122
DEFAULT_PAGINATION_SIZE = env("DEFAULT_PAGINATION_SIZE", default=50)
139123

140124
REST_FRAMEWORK = {
@@ -283,4 +267,35 @@
283267
EMAIL_USE_SSL = os.getenv("EMAIL_USE_SSL", "False") == "True"
284268
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER", "example-email@example.com")
285269
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "example-email-password")
286-
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "no-reply@example.com")
270+
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "no-reply@example.com")
271+
272+
273+
# CORS settings
274+
275+
276+
def extract_domain(url):
277+
return urlparse(url).hostname
278+
279+
280+
if DEBUG:
281+
CORS_ORIGIN_ALLOW_ALL = True
282+
else:
283+
CORS_ORIGIN_ALLOW_ALL = env("CORS_ORIGIN_ALLOW_ALL", default=False)
284+
285+
CORS_ALLOWED_ORIGINS = env(
286+
"CORS_ALLOWED_ORIGINS", default="http://127.0.0.1:8000"
287+
).split(",")
288+
289+
CORS_ALLOW_HEADERS = list(default_headers) + [
290+
"access-token",
291+
"authorization",
292+
"content-type",
293+
"x-csrftoken",
294+
]
295+
ALLOWED_HOSTS = [
296+
"localhost",
297+
"127.0.0.1",
298+
env("HOSTNAME", default="127.0.0.1"),
299+
gethostname(),
300+
gethostbyname(gethostname()),
301+
] + [extract_domain(url) for url in CORS_ALLOWED_ORIGINS if url]

0 commit comments

Comments
 (0)