fix: don't require secret if auth disabled

This commit is contained in:
Leon
2025-07-19 10:46:43 +02:00
parent ab45139e7e
commit 830fcc5757
3 changed files with 22 additions and 5 deletions

View File

@@ -46,6 +46,8 @@ def _get_auth_credentials(db: Session) -> dict:
def create_access_token(data: dict, expires_delta: timedelta | None = None): def create_access_token(data: dict, expires_delta: timedelta | None = None):
"""Create a new access token.""" """Create a new access token."""
if not env_settings.secret_key:
raise ValueError("SECRET_KEY is not set, cannot create access tokens.")
to_encode = data.copy() to_encode = data.copy()
if expires_delta: if expires_delta:
expire = datetime.now(UTC) + expires_delta expire = datetime.now(UTC) + expires_delta
@@ -81,6 +83,14 @@ def protected_route(
detail="Could not validate credentials", detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"}, headers={"WWW-Authenticate": "Bearer"},
) )
if not env_settings.secret_key:
# This is an internal server error because auth is configured but the key is missing.
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="SECRET_KEY is not configured on the server.",
)
try: try:
payload = jwt.decode( payload = jwt.decode(
token, env_settings.secret_key, algorithms=[env_settings.algorithm] token, env_settings.secret_key, algorithms=[env_settings.algorithm]

View File

@@ -29,8 +29,9 @@ class Settings(BaseSettings):
auto_add_new_senders: bool = False auto_add_new_senders: bool = False
auth_username: str | None = None auth_username: str | None = None
auth_password: str | None = None auth_password: str | None = None
secret_key: str = Field( secret_key: str | None = Field(
..., validation_alias=AliasChoices("SECRET_KEY", "LETTERFEED_SECRET_KEY") default=None,
validation_alias=AliasChoices("SECRET_KEY", "LETTERFEED_SECRET_KEY"),
) )
algorithm: str = "HS256" algorithm: str = "HS256"
access_token_expire_minutes: int = 30 access_token_expire_minutes: int = 30

View File

@@ -49,7 +49,13 @@ def login_for_access_token(
) )
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes) access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
access_token = create_access_token( try:
data={"sub": form_data.username}, expires_delta=access_token_expires access_token = create_access_token(
) data={"sub": form_data.username}, expires_delta=access_token_expires
)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e),
)
return {"access_token": access_token, "token_type": "bearer"} return {"access_token": access_token, "token_type": "bearer"}