Skip to content

Commit

Permalink
fix(backend): building of extra cors origins, type mismatch
Browse files Browse the repository at this point in the history
  • Loading branch information
spwoodcock committed Nov 14, 2024
1 parent e004d26 commit c55aef2
Showing 1 changed file with 31 additions and 35 deletions.
66 changes: 31 additions & 35 deletions src/backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,49 +158,45 @@ class Settings(BaseSettings):
FMTM_DOMAIN: str
FMTM_DEV_PORT: Optional[str] = "7050"

EXTRA_CORS_ORIGINS: Optional[str | list[str]] = []
EXTRA_CORS_ORIGINS: Optional[str | list[str]] = None

@field_validator("EXTRA_CORS_ORIGINS", mode="before")
@classmethod
def assemble_cors_origins(
cls,
extra_origins: Optional[str | list[str]],
extra_origins: Optional[Union[str, list[str]]],
info: ValidationInfo,
) -> Union[list[str], str]:
"""Build and validate CORS origins list.
By default, the provided frontend URLs are included in the origins list.
If this variable used, the provided urls are appended to the list.
"""
# If a string is passed, convert to list
if isinstance(extra_origins, str):
default_origins = [i.strip() for i in extra_origins.split(",")]
else:
default_origins = []

# Add XLSForm editor url by default
default_origins += ["https://xlsforms.fmtm.dev"]

# Handle localhost / testing scenario
if "localhost" in (domain := info.data.get("FMTM_DOMAIN")):
dev_port = info.data.get("FMTM_DEV_PORT", "false")
if dev_port.lower() in ("0", "no", "false", ""):
local_server_port = ""
else:
local_server_port = f":{dev_port}"
) -> list[str]:
"""Build and validate CORS origins list."""
# Initialize default origins
default_origins = ["https://xlsforms.fmtm.dev"]

# Handle localhost/testing scenario
domain = info.data.get("FMTM_DOMAIN", "localhost")
dev_port = info.data.get("FMTM_DEV_PORT", "")
if "localhost" in domain:
local_server_port = (
f":{dev_port}"
if dev_port and dev_port.lower() not in ("0", "no", "false")
else ""
)
default_origins.append(f"http://{domain}{local_server_port}")
return default_origins

# Add the main FMTM domain
default_origins.append(f"https://{domain}")

# If no extra origins, return frontend + XLSForm editor URLs
if extra_origins is None:
return default_origins
# Else add extra origins to defaults
else:
default_origins.append(extra_origins)
return default_origins
# Add the main FMTM domain
default_origins.append(f"https://{domain}")

# Process `extra_origins` if provided
if isinstance(extra_origins, str):
# Split by comma and strip whitespace
extra_origins_list = [
i.strip() for i in extra_origins.split(",") if i.strip()
]
default_origins.extend(extra_origins_list)
elif isinstance(extra_origins, list):
default_origins.extend(extra_origins)

# Ensure uniqueness and return (remove dups)
return list(dict.fromkeys(default_origins))

API_PREFIX: str = ""

Expand Down

0 comments on commit c55aef2

Please sign in to comment.