Make auth toggle a settings option instead of env var
Some checks failed
CI / style (push) Has been cancelled
CI / build-client (push) Has been cancelled
CI / build-tester (push) Has been cancelled
CI / build-amd64 (push) Has been cancelled
CI / test (cockroachdb) (push) Has been cancelled
CI / test (mariadb) (push) Has been cancelled
CI / test (postgres) (push) Has been cancelled
CI / test (sqlite) (push) Has been cancelled
CI / build-arm64 (push) Has been cancelled
CI / build-armv7 (push) Has been cancelled
CI / publish-images (push) Has been cancelled
CI / publish-release (push) Has been cancelled
Issue Manager / issue-manager (push) Has been cancelled
Some checks failed
CI / style (push) Has been cancelled
CI / build-client (push) Has been cancelled
CI / build-tester (push) Has been cancelled
CI / build-amd64 (push) Has been cancelled
CI / test (cockroachdb) (push) Has been cancelled
CI / test (mariadb) (push) Has been cancelled
CI / test (postgres) (push) Has been cancelled
CI / test (sqlite) (push) Has been cancelled
CI / build-arm64 (push) Has been cancelled
CI / build-armv7 (push) Has been cancelled
CI / publish-images (push) Has been cancelled
CI / publish-release (push) Has been cancelled
Issue Manager / issue-manager (push) Has been cancelled
- Auth enabled state now stored in database setting (auth_enabled) - Add POST /auth/toggle endpoint to enable/disable auth from UI - Add auth toggle section to Settings > General page - Enabling auth without users prompts to create first admin - Disabling auth requires admin password confirmation - Auth setting cached in memory and loaded on startup Removes need for SPOOLMAN_AUTH_ENABLED env var Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"""Authentication API endpoints."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Optional
|
||||
@@ -22,9 +23,11 @@ from spoolman.auth import (
|
||||
get_password_hash,
|
||||
get_user_by_username,
|
||||
is_auth_enabled,
|
||||
set_auth_enabled_cache,
|
||||
)
|
||||
from spoolman.database import models
|
||||
from spoolman.database.database import get_db_session
|
||||
from spoolman.settings import SETTINGS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -287,3 +290,85 @@ async def delete_user(
|
||||
|
||||
logger.info("User deleted: %s", user.username)
|
||||
return {"message": "User deleted"}
|
||||
|
||||
|
||||
class AuthToggleRequest(BaseModel):
|
||||
"""Request to enable or disable authentication."""
|
||||
|
||||
enabled: bool
|
||||
password: Optional[str] = Field(None, description="Admin password required when disabling auth")
|
||||
|
||||
|
||||
@router.post(
|
||||
"/toggle",
|
||||
name="Toggle authentication",
|
||||
description="Enable or disable authentication. Requires admin password to disable.",
|
||||
response_model=AuthStatusResponse,
|
||||
)
|
||||
async def toggle_auth(
|
||||
body: AuthToggleRequest,
|
||||
db: Annotated[AsyncSession, Depends(get_db_session)],
|
||||
) -> AuthStatusResponse:
|
||||
"""Enable or disable authentication."""
|
||||
# Get current user count
|
||||
result = await db.execute(select(func.count()).select_from(models.User))
|
||||
user_count = result.scalar() or 0
|
||||
|
||||
if body.enabled:
|
||||
# Enabling auth
|
||||
if user_count == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot enable auth without users. Use /auth/setup to create the first admin user.",
|
||||
)
|
||||
else:
|
||||
# Disabling auth - require admin password for security
|
||||
if not body.password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Admin password required to disable authentication",
|
||||
)
|
||||
|
||||
# Find any admin user and verify password
|
||||
result = await db.execute(
|
||||
select(models.User).where(models.User.role == Role.ADMIN.value, models.User.is_active == True) # noqa: E712
|
||||
)
|
||||
admin_users = result.scalars().all()
|
||||
|
||||
if not admin_users:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No active admin user found",
|
||||
)
|
||||
|
||||
# Check if password matches any admin
|
||||
password_valid = False
|
||||
for admin in admin_users:
|
||||
if auth.verify_password(body.password, admin.hashed_password):
|
||||
password_valid = True
|
||||
break
|
||||
|
||||
if not password_valid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid admin password",
|
||||
)
|
||||
|
||||
# Update the setting in database
|
||||
setting = models.Setting(
|
||||
key="auth_enabled",
|
||||
value=json.dumps(body.enabled),
|
||||
last_updated=datetime.utcnow().replace(microsecond=0),
|
||||
)
|
||||
await db.merge(setting)
|
||||
await db.commit()
|
||||
|
||||
# Update the cache
|
||||
set_auth_enabled_cache(body.enabled)
|
||||
|
||||
logger.info("Authentication %s", "enabled" if body.enabled else "disabled")
|
||||
|
||||
return AuthStatusResponse(
|
||||
enabled=body.enabled,
|
||||
has_users=user_count > 0,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user