diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 3702f06..eeee36a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -27,6 +27,20 @@ jobs: enable-cache: false version: "0.9.12" + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + + - name: Build frontend + working-directory: frontend + run: | + bun install --frozen-lockfile + bun run build + + - name: Copy frontend build into package static directory + run: | + rm -rf src/litestar_admin/static + cp -r frontend/out src/litestar_admin/static + - name: Build package run: uv build @@ -95,7 +109,7 @@ jobs: args: --current --strip header - name: Create GitHub Release (Draft) - uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2 + uses: softprops/action-gh-release@26e8ad27a09a225049a7075d7ec1caa2df6ff332 # v2.6.0 with: draft: true files: | @@ -138,7 +152,7 @@ jobs: contents: write steps: - name: Mark Release as Published - uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2 + uses: softprops/action-gh-release@26e8ad27a09a225049a7075d7ec1caa2df6ff332 # v2.6.0 with: draft: false diff --git a/Makefile b/Makefile index ce0d57a..60a6923 100644 --- a/Makefile +++ b/Makefile @@ -199,7 +199,7 @@ frontend-build: ## Build frontend without copying ##@ Build & Release -build: clean ## Build package +build: clean frontend ## Build package (includes frontend) @uv build clean: ## Clean build artifacts and caches diff --git a/docs/conf.py b/docs/conf.py index 505933d..9836a6b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,11 +2,11 @@ from __future__ import annotations -import os import sys +from pathlib import Path # Add source directory to path for autodoc -sys.path.insert(0, os.path.abspath("../src")) +sys.path.insert(0, str(Path("../src").resolve())) # Project information project = "litestar-admin" diff --git a/pyproject.toml b/pyproject.toml index b528fbe..eb7ae38 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ dependencies = [ "advanced-alchemy>=0.10.0", "sqlalchemy[asyncio]>=2.0.0", "aiofiles>=25.1.0", + "typing-extensions>=4.0.0; python_version < '3.11'", ] [project.optional-dependencies] @@ -138,6 +139,7 @@ max-complexity = 12 ] "examples/**/*" = ["ARG", "B008", "D", "FAST", "FBT", "PLR1714", "RET504", "RUF012", "S101", "S104", "S106", "SIM108", "T201", "TC002"] "src/litestar_admin/controllers/**/*" = ["B008"] # Litestar Parameter defaults +"docs/conf.py" = ["INP001"] # Sphinx config, not a package module [tool.ruff.lint.pydocstyle] convention = "google" diff --git a/src/litestar_admin/audit/middleware.py b/src/litestar_admin/audit/middleware.py index 82b57ac..be56131 100644 --- a/src/litestar_admin/audit/middleware.py +++ b/src/litestar_admin/audit/middleware.py @@ -20,8 +20,9 @@ import contextlib import re from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any +from litestar.enums import ScopeType from litestar.middleware import AbstractMiddleware from litestar.status_codes import HTTP_200_OK, HTTP_300_MULTIPLE_CHOICES @@ -107,7 +108,7 @@ class AuditMiddleware(AbstractMiddleware): middleware = AuditMiddleware(logger, config=config) """ - scopes: ClassVar[set[str]] = {"http"} + scopes = {ScopeType.HTTP} # noqa: RUF012 def __init__( self, diff --git a/src/litestar_admin/auth/models.py b/src/litestar_admin/auth/models.py index ed29704..27b3c8c 100644 --- a/src/litestar_admin/auth/models.py +++ b/src/litestar_admin/auth/models.py @@ -34,9 +34,15 @@ class CustomAdminUser(AdminUserBase): from __future__ import annotations +import sys import uuid from datetime import datetime, timezone -from typing import Any, ClassVar, Self +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING or sys.version_info < (3, 11): + from typing_extensions import Self +else: + from typing import Self from sqlalchemy import JSON, Boolean, DateTime, Index, String from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -123,7 +129,7 @@ class AdminUser(AdminUserBase): await session.commit() """ - __tablename__: ClassVar[str] = "admin_users" + __tablename__ = "admin_users" # Primary key id: Mapped[str] = mapped_column( diff --git a/src/litestar_admin/auth/password.py b/src/litestar_admin/auth/password.py index 58965e7..390a455 100644 --- a/src/litestar_admin/auth/password.py +++ b/src/litestar_admin/auth/password.py @@ -166,10 +166,11 @@ def hash(self, password: str) -> str: >>> hashed.startswith("$argon2") # If Argon2 is available True """ - if not PasswordHasher._available or PasswordHasher._context is None: + context = PasswordHasher._context + if not PasswordHasher._available or context is None: msg = "No password hashing backend available. Install 'litestar-admin[auth]' or 'passlib[argon2]'." raise RuntimeError(msg) - return PasswordHasher._context.hash(password) # type: ignore[union-attr] + return context.hash(password) def verify(self, password: str, password_hash: str) -> bool: """Verify a password against its hash. @@ -192,10 +193,11 @@ def verify(self, password: str, password_hash: str) -> bool: >>> hasher.verify("wrong_password", hashed) False """ - if not PasswordHasher._available or PasswordHasher._context is None: + context = PasswordHasher._context + if not PasswordHasher._available or context is None: msg = "No password hashing backend available. Install 'litestar-admin[auth]' or 'passlib[argon2]'." raise RuntimeError(msg) - return PasswordHasher._context.verify(password, password_hash) # type: ignore[union-attr] + return context.verify(password, password_hash) def needs_rehash(self, password_hash: str) -> bool: """Check if a password hash needs to be rehashed. @@ -221,10 +223,11 @@ def needs_rehash(self, password_hash: str) -> bool: ... # Verify and rehash on next login ... pass """ - if not PasswordHasher._available or PasswordHasher._context is None: + context = PasswordHasher._context + if not PasswordHasher._available or context is None: msg = "No password hashing backend available. Install 'litestar-admin[auth]' or 'passlib[argon2]'." raise RuntimeError(msg) - return PasswordHasher._context.needs_update(password_hash) # type: ignore[union-attr] + return context.needs_update(password_hash) @classmethod def is_available(cls) -> bool: diff --git a/src/litestar_admin/contrib/providers/in_memory.py b/src/litestar_admin/contrib/providers/in_memory.py index b0f7473..d499778 100644 --- a/src/litestar_admin/contrib/providers/in_memory.py +++ b/src/litestar_admin/contrib/providers/in_memory.py @@ -6,7 +6,9 @@ from __future__ import annotations +import operator import uuid +from collections.abc import Callable from typing import Any, ClassVar, Literal from litestar_admin.views.custom import CustomView, ListResult @@ -14,6 +16,44 @@ __all__ = ["InMemoryView"] +def _numeric_or_string_comparator(compare: Callable[[Any, Any], bool]) -> Callable[[Any, Any, str, str], bool]: + """Build a filter comparator that compares numerically, falling back to strings. + + Args: + compare: A two-argument comparison function (e.g. operator.gt). + + Returns: + A comparator matching the `_FILTER_OPERATORS` signature. + """ + + def _compare(item_value: Any, value: Any, str_item_value: str, str_value: str) -> bool: + try: + return compare(float(item_value), float(value)) + except (ValueError, TypeError): + return compare(str_item_value, str_value) + + return _compare + + +_FILTER_OPERATORS: dict[str, Callable[[Any, Any, str, str], bool]] = { + "equals": lambda iv, v, _siv, _sv: str(iv) == str(v), + "notEquals": lambda iv, v, _siv, _sv: str(iv) != str(v), + "contains": lambda _iv, _v, siv, sv: sv in siv, + "startsWith": lambda _iv, _v, siv, sv: siv.startswith(sv), + "endsWith": lambda _iv, _v, siv, sv: siv.endswith(sv), + "isEmpty": lambda iv, _v, _siv, _sv: not iv or iv == "", + "isNotEmpty": lambda iv, _v, _siv, _sv: bool(iv) and iv != "", + "gt": _numeric_or_string_comparator(operator.gt), + "greaterThan": _numeric_or_string_comparator(operator.gt), + "gte": _numeric_or_string_comparator(operator.ge), + "greaterThanOrEqual": _numeric_or_string_comparator(operator.ge), + "lt": _numeric_or_string_comparator(operator.lt), + "lessThan": _numeric_or_string_comparator(operator.lt), + "lte": _numeric_or_string_comparator(operator.le), + "lessThanOrEqual": _numeric_or_string_comparator(operator.le), +} + + class InMemoryView(CustomView): """CustomView backed by an in-memory data store. @@ -270,55 +310,14 @@ def _apply_filter_operator( if value is None: return items + matcher = _FILTER_OPERATORS.get(operator, _FILTER_OPERATORS["equals"]) + str_value = str(value).lower() result = [] for item in items: item_value = item.get(field) if item_value is None: continue - - match = False - str_item_value = str(item_value).lower() - str_value = str(value).lower() - - if operator == "equals": - match = str(item_value) == str(value) - elif operator == "contains": - match = str_value in str_item_value - elif operator == "startsWith": - match = str_item_value.startswith(str_value) - elif operator == "endsWith": - match = str_item_value.endswith(str_value) - elif operator in ("gt", "greaterThan"): - try: - match = float(item_value) > float(value) - except (ValueError, TypeError): - match = str_item_value > str_value - elif operator in ("gte", "greaterThanOrEqual"): - try: - match = float(item_value) >= float(value) - except (ValueError, TypeError): - match = str_item_value >= str_value - elif operator in ("lt", "lessThan"): - try: - match = float(item_value) < float(value) - except (ValueError, TypeError): - match = str_item_value < str_value - elif operator in ("lte", "lessThanOrEqual"): - try: - match = float(item_value) <= float(value) - except (ValueError, TypeError): - match = str_item_value <= str_value - elif operator == "notEquals": - match = str(item_value) != str(value) - elif operator == "isEmpty": - match = not item_value or item_value == "" - elif operator == "isNotEmpty": - match = bool(item_value) and item_value != "" - else: - # Default to equality - match = str(item_value) == str(value) - - if match: + if matcher(item_value, value, str(item_value).lower(), str_value): result.append(item) return result diff --git a/src/litestar_admin/controllers/auth.py b/src/litestar_admin/controllers/auth.py index 8b53ee0..aec89e8 100644 --- a/src/litestar_admin/controllers/auth.py +++ b/src/litestar_admin/controllers/auth.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING from litestar import Controller, get, post from litestar.exceptions import NotAuthorizedException, PermissionDeniedException @@ -139,7 +139,7 @@ class AuthController(Controller): """ path = "/api/auth" - tags: ClassVar[list[str]] = ["Authentication"] + tags = ("Authentication",) @post( "/login", diff --git a/src/litestar_admin/controllers/bulk.py b/src/litestar_admin/controllers/bulk.py index 6afdb9d..396c382 100644 --- a/src/litestar_admin/controllers/bulk.py +++ b/src/litestar_admin/controllers/bulk.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any from litestar import Controller, post from litestar.exceptions import HTTPException, NotFoundException @@ -127,7 +127,7 @@ async def bulk_activate( """ path = "/api/models" - tags: ClassVar[list[str]] = ["Bulk Actions"] + tags = ("Bulk Actions",) @post( "/{model_name:str}/bulk/delete", @@ -324,4 +324,4 @@ def _get_view_or_raise( status_code=HTTP_404_NOT_FOUND, detail=f"Model '{model_name}' not found", ) - return registry.get_view_by_name(model_name) + return registry.get_model_view_by_name(model_name) diff --git a/src/litestar_admin/controllers/config.py b/src/litestar_admin/controllers/config.py index ef38794..93abb64 100644 --- a/src/litestar_admin/controllers/config.py +++ b/src/litestar_admin/controllers/config.py @@ -3,7 +3,6 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import ClassVar from litestar import Controller, get from litestar.status_codes import HTTP_200_OK @@ -84,7 +83,7 @@ class ConfigController(Controller): """ path = "/api/config" - tags: ClassVar[list[str]] = ["Configuration"] + tags = ("Configuration",) @get( "/", @@ -130,26 +129,25 @@ async def get_config( ) ) # Also check if auth_backend has OAuth providers - elif admin_config.auth_backend is not None: - if hasattr(admin_config.auth_backend, "available_providers"): - provider_names = admin_config.auth_backend.available_providers - base_url = admin_config.base_url - for name in provider_names: - # Create display name (capitalize, handle special cases) - display_name = { - "github": "GitHub", - "google": "Google", - "discord": "Discord", - "demo": "Demo", - }.get(name, name.title()) - - oauth_providers.append( - OAuthProvider( - name=name, - display_name=display_name, - login_url=f"{base_url}/auth/oauth/{name}/login", - ) + elif admin_config.auth_backend is not None and hasattr(admin_config.auth_backend, "available_providers"): + provider_names = admin_config.auth_backend.available_providers + base_url = admin_config.base_url + for name in provider_names: + # Create display name (capitalize, handle special cases) + display_name = { + "github": "GitHub", + "google": "Google", + "discord": "Discord", + "demo": "Demo", + }.get(name, name.title()) + + oauth_providers.append( + OAuthProvider( + name=name, + display_name=display_name, + login_url=f"{base_url}/auth/oauth/{name}/login", ) + ) return ConfigResponse( title=admin_config.title, diff --git a/src/litestar_admin/controllers/custom_views.py b/src/litestar_admin/controllers/custom_views.py index 6500646..e52ee2d 100644 --- a/src/litestar_admin/controllers/custom_views.py +++ b/src/litestar_admin/controllers/custom_views.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast +from typing import TYPE_CHECKING, Any, Literal, cast from litestar import Controller, Request, delete, get, post, put from litestar.exceptions import NotFoundException, PermissionDeniedException @@ -368,7 +368,7 @@ class CustomViewsController(Controller): """ path = "/api/views/custom" - tags: ClassVar[list[str]] = ["Custom Views"] + tags = ("Custom Views",) @get( "/", @@ -458,10 +458,7 @@ async def list_items( effective_limit = limit or page_size or 25 effective_limit = min(max(1, effective_limit), 100) - if offset is not None: - effective_page = (offset // effective_limit) + 1 - else: - effective_page = page or 1 + effective_page = (offset // effective_limit) + 1 if offset is not None else (page or 1) effective_page = max(1, effective_page) # Parse filters if provided @@ -767,7 +764,7 @@ class ActionsController(Controller): """ path = "/api/views/actions" - tags: ClassVar[list[str]] = ["Actions"] + tags = ("Actions",) @get( "/", @@ -925,7 +922,7 @@ class PagesController(Controller): """ path = "/api/views/pages" - tags: ClassVar[list[str]] = ["Pages"] + tags = ("Pages",) @get( "/", @@ -1099,7 +1096,7 @@ class EmbedsController(Controller): """ path = "/api/views/embeds" - tags: ClassVar[list[str]] = ["Embeds"] + tags = ("Embeds",) @get( "/", @@ -1247,7 +1244,7 @@ class LinksController(Controller): """ path = "/api/views/links" - tags: ClassVar[list[str]] = ["Links"] + tags = ("Links",) @get( "/", diff --git a/src/litestar_admin/controllers/dashboard.py b/src/litestar_admin/controllers/dashboard.py index fa155e3..3dc60f2 100644 --- a/src/litestar_admin/controllers/dashboard.py +++ b/src/litestar_admin/controllers/dashboard.py @@ -4,7 +4,7 @@ from dataclasses import dataclass, field from datetime import datetime -from typing import Any, ClassVar +from typing import Any from litestar import Controller, get from litestar.status_codes import HTTP_200_OK @@ -115,7 +115,7 @@ class DashboardController(Controller): """ path = "/api/dashboard" - tags: ClassVar[list[str]] = ["Dashboard"] + tags = ("Dashboard",) @get( "/stats", diff --git a/src/litestar_admin/controllers/export.py b/src/litestar_admin/controllers/export.py index 55abdb4..2f85b00 100644 --- a/src/litestar_admin/controllers/export.py +++ b/src/litestar_admin/controllers/export.py @@ -6,7 +6,7 @@ import json from dataclasses import dataclass from io import BytesIO, StringIO -from typing import TYPE_CHECKING, Any, ClassVar, Literal +from typing import TYPE_CHECKING, Any, Literal from litestar import Controller, get, post from litestar.exceptions import NotFoundException, ValidationException @@ -95,7 +95,7 @@ class ExportController(Controller): """ path = "/api/models" - tags: ClassVar[list[str]] = ["Export"] + tags = ("Export",) @get( "/{model_name:str}/export", @@ -262,7 +262,7 @@ def _get_view_class( if not registry.has_model_by_name(model_name): msg = f"Model '{model_name}' not found" raise NotFoundException(msg) - return registry.get_view_by_name(model_name) + return registry.get_model_view_by_name(model_name) @staticmethod def _get_primary_key_column(model: type[Any]) -> str: diff --git a/src/litestar_admin/controllers/files.py b/src/litestar_admin/controllers/files.py index fa7ceb4..438d4d1 100644 --- a/src/litestar_admin/controllers/files.py +++ b/src/litestar_admin/controllers/files.py @@ -14,7 +14,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any, ClassVar +from typing import Any from litestar import Controller, Request, delete, get, post from litestar.datastructures import UploadFile # Required for runtime signature @@ -24,17 +24,12 @@ from litestar.response import Redirect, Response from litestar.status_codes import HTTP_200_OK, HTTP_201_CREATED +from litestar_admin.contrib.storages import AdminStorageBackend # noqa: TC001 - Required at runtime for Litestar DI +from litestar_admin.fields.file import FileField, ImageField, validate_file_field from litestar_admin.logging import get_logger _logger = get_logger(__name__) -from litestar_admin.contrib.storages import AdminStorageBackend -from litestar_admin.fields.file import ( - FileField, - ImageField, - validate_file_field, -) - __all__ = [ "DeleteFileResponse", "FileInfoResponse", @@ -169,7 +164,7 @@ class FilesController(Controller): """ path = "/api/files" - tags: ClassVar[list[str]] = ["Files"] + tags = ("Files",) @post( "/upload", @@ -189,13 +184,8 @@ async def upload_file( optional thumbnail generation. Args: + request: The incoming request, used to read query params and form data. admin_storage: The storage backend for file operations. - data: The uploaded file from the multipart form. - model_name: The name of the model this file belongs to. - field_name: The name of the field this file belongs to. - allowed_extensions: Comma-separated list of allowed extensions. - max_size: Maximum file size in bytes. - generate_thumbnail: Whether to generate a thumbnail (for images). Returns: UploadFileResponse on success, or validation error response. @@ -203,7 +193,6 @@ async def upload_file( Raises: ValidationException: If the file fails validation. """ - # Get query params model_name = request.query_params.get("model_name", "unknown") field_name = request.query_params.get("field_name", "file") allowed_extensions = request.query_params.get("allowed_extensions") @@ -211,162 +200,48 @@ async def upload_file( max_size = int(max_size_str) if max_size_str else None generate_thumbnail = request.query_params.get("generate_thumbnail", "false").lower() == "true" - # Debug logging - _logger.info("=== FILE UPLOAD DEBUG ===") - _logger.info(f"model_name: {model_name}") - _logger.info(f"field_name: {field_name}") - _logger.info(f"admin_storage: {admin_storage}") - _logger.info(f"Content-Type: {request.headers.get('content-type')}") - - # Check if storage is configured if admin_storage is None: - _logger.error("Storage not configured!") - return Response( - content=ValidationErrorResponse( - success=False, - errors=[ - { - "field": field_name, - "error": "File storage is not configured. Configure storage in AdminConfig.", - } - ], - ), - status_code=HTTP_200_OK, + _logger.error("Storage not configured for file upload") + return self._file_error_response( + field_name, "File storage is not configured. Configure storage in AdminConfig." ) - # Get uploaded file from form data try: form_data = await request.form() - _logger.info(f"Form data keys: {list(form_data.keys())}") - for key, value in form_data.items(): - _logger.info( - f" {key}: {type(value).__name__} = {value if not isinstance(value, UploadFile) else f'UploadFile({value.filename})'}" - ) except Exception as e: - _logger.error(f"Error parsing form data: {e}") - return Response( - content=ValidationErrorResponse( - success=False, - errors=[ - { - "field": field_name, - "error": f"Error parsing form data: {e}", - } - ], - ), - status_code=HTTP_200_OK, - ) + _logger.exception("Error parsing form data") + return self._file_error_response(field_name, f"Error parsing form data: {e}") data = form_data.get("data") - _logger.info(f"data field: {type(data).__name__ if data else 'None'}") if not isinstance(data, UploadFile): - return Response( - content=ValidationErrorResponse( - success=False, - errors=[ - { - "field": field_name, - "error": "No file uploaded. Please select a file.", - } - ], - ), - status_code=HTTP_200_OK, - ) + return self._file_error_response(field_name, "No file uploaded. Please select a file.") - # Read file content file_content = await data.read() - _logger.info(f"File content length: {len(file_content)} bytes") - - # Only validate if explicit restrictions are provided - # Otherwise allow any file type through the generic endpoint - if allowed_extensions or max_size: - extensions_list = None - if allowed_extensions: - extensions_list = [ext.strip() for ext in allowed_extensions.split(",")] - - if generate_thumbnail: - field_config: FileField = ImageField( - name=field_name, - allowed_extensions=extensions_list, - max_size=max_size, - generate_thumbnail=True, - ) - else: - field_config = FileField( - name=field_name, - allowed_extensions=extensions_list, - max_size=max_size, - ) - _logger.info(f"File config: extensions={extensions_list}, max_size={max_size}") - - # Validate the file - validation_errors = validate_file_field(data, field_config, file_content=file_content) - _logger.info(f"Validation errors: {validation_errors}") - - if validation_errors: - for err in validation_errors: - _logger.error(f"Validation error: field={err.field_name}, error={err.error}, code={err.error_code}") - return Response( - content=ValidationErrorResponse( - success=False, - errors=[ - { - "field": err.field_name, - "error": err.error, - "code": err.error_code, - } - for err in validation_errors - ], - ), - status_code=422, - ) - else: - _logger.info("No validation restrictions specified, allowing any file type") - field_config = None + field_config, error_response = self._validate_upload( + data, + file_content, + field_name, + allowed_extensions=allowed_extensions, + max_size=max_size, + generate_thumbnail=generate_thumbnail, + ) + if error_response is not None: + return error_response - # Upload the file try: - _logger.info(f"Starting upload to storage... generate_thumbnail={generate_thumbnail}") - # Generate thumbnail if requested (regardless of validation config) - should_generate_thumb = generate_thumbnail or ( - isinstance(field_config, ImageField) and field_config.generate_thumbnail + storage_path, thumbnail_path, thumbnail_url, public_url = await self._store_upload( + admin_storage, + file_content, + data.filename or "unnamed", + model_name, + field_name, + generate_thumbnail=generate_thumbnail, + field_config=field_config, ) - if should_generate_thumb: - storage_path, thumbnail_path = await admin_storage.upload_with_thumbnail( - file_content=file_content, - filename=data.filename or "unnamed", - model_name=model_name, - field_name=field_name, - ) - thumbnail_url = admin_storage.get_public_url(thumbnail_path) if thumbnail_path else None - _logger.info(f"Thumbnail generated: {thumbnail_path} -> {thumbnail_url}") - else: - storage_path = await admin_storage.upload( - file_content=file_content, - filename=data.filename or "unnamed", - model_name=model_name, - field_name=field_name, - ) - thumbnail_path = None - thumbnail_url = None - - public_url = admin_storage.get_public_url(storage_path) - _logger.info(f"Upload successful: {storage_path} -> {public_url}") except Exception as e: - _logger.error(f"Upload failed: {e}", exc_info=True) - return Response( - content=ValidationErrorResponse( - success=False, - errors=[ - { - "field": field_name, - "error": f"Upload failed: {e}", - } - ], - ), - status_code=500, - ) + _logger.exception("Upload failed") + return self._file_error_response(field_name, f"Upload failed: {e}", status_code=500) return UploadFileResponse( success=True, @@ -379,6 +254,125 @@ async def upload_file( thumbnail_url=thumbnail_url, ) + @staticmethod + def _file_error_response( + field_name: str, message: str, status_code: int = HTTP_200_OK + ) -> Response[ValidationErrorResponse]: + """Build a single-field validation error response. + + Args: + field_name: The field the error applies to. + message: The human-readable error message. + status_code: The HTTP status code to return. + + Returns: + A Response wrapping a ValidationErrorResponse. + """ + return Response( + content=ValidationErrorResponse(success=False, errors=[{"field": field_name, "error": message}]), + status_code=status_code, + ) + + @staticmethod + def _validate_upload( + data: UploadFile, + file_content: bytes, + field_name: str, + *, + allowed_extensions: str | None, + max_size: int | None, + generate_thumbnail: bool, + ) -> tuple[FileField | None, Response[ValidationErrorResponse] | None]: + """Validate an uploaded file against field restrictions, if any were given. + + Args: + data: The uploaded file. + file_content: The raw file bytes. + field_name: The name of the field the file belongs to. + allowed_extensions: Comma-separated list of allowed extensions. + max_size: Maximum file size in bytes. + generate_thumbnail: Whether a thumbnail should be generated for images. + + Returns: + A tuple of the resolved field config (or None if no restrictions were + requested) and an error response (or None if validation passed). + """ + if not (allowed_extensions or max_size): + return None, None + + extensions_list = [ext.strip() for ext in allowed_extensions.split(",")] if allowed_extensions else None + field_config: FileField = ( + ImageField(name=field_name, allowed_extensions=extensions_list, max_size=max_size, generate_thumbnail=True) + if generate_thumbnail + else FileField(name=field_name, allowed_extensions=extensions_list, max_size=max_size) + ) + + validation_errors = validate_file_field(data, field_config, file_content=file_content) + if not validation_errors: + return field_config, None + + for err in validation_errors: + _logger.error("Validation error: field=%s, error=%s, code=%s", err.field_name, err.error, err.error_code) + return field_config, Response( + content=ValidationErrorResponse( + success=False, + errors=[ + {"field": err.field_name, "error": err.error, "code": err.error_code} for err in validation_errors + ], + ), + status_code=422, + ) + + @staticmethod + async def _store_upload( + admin_storage: AdminStorageBackend, + file_content: bytes, + filename: str, + model_name: str, + field_name: str, + *, + generate_thumbnail: bool, + field_config: FileField | None, + ) -> tuple[str, str | None, str | None, str]: + """Store an uploaded file, generating a thumbnail if requested. + + Args: + admin_storage: The storage backend for file operations. + file_content: The raw file bytes. + filename: The original filename. + model_name: The name of the model this file belongs to. + field_name: The name of the field this file belongs to. + generate_thumbnail: Whether a thumbnail should be generated for images. + field_config: The resolved field config, if validation ran. + + Returns: + A tuple of (storage_path, thumbnail_path, thumbnail_url, public_url). + """ + should_generate_thumb = generate_thumbnail or ( + isinstance(field_config, ImageField) and field_config.generate_thumbnail + ) + if should_generate_thumb: + storage_path, thumbnail_path = await admin_storage.upload_with_thumbnail( + file_content=file_content, + filename=filename, + model_name=model_name, + field_name=field_name, + ) + thumbnail_url = admin_storage.get_public_url(thumbnail_path) if thumbnail_path else None + else: + storage_path = await admin_storage.upload( + file_content=file_content, + filename=filename, + model_name=model_name, + field_name=field_name, + ) + thumbnail_path = None + thumbnail_url = None + + public_url = admin_storage.get_public_url(storage_path) + _logger.info("Upload successful: %s -> %s", storage_path, public_url) + return storage_path, thumbnail_path, thumbnail_url, public_url + @post( "/upload/validate", status_code=HTTP_200_OK, diff --git a/src/litestar_admin/controllers/import_data.py b/src/litestar_admin/controllers/import_data.py index 10991f3..181b676 100644 --- a/src/litestar_admin/controllers/import_data.py +++ b/src/litestar_admin/controllers/import_data.py @@ -8,7 +8,7 @@ import re from dataclasses import dataclass, field from datetime import datetime -from typing import TYPE_CHECKING, Any, ClassVar, Literal +from typing import TYPE_CHECKING, Any, Literal from litestar import Controller, post from litestar.datastructures import UploadFile # noqa: TC002 - Required at runtime for Litestar DI @@ -219,7 +219,7 @@ class ImportController(Controller): """ path = "/api/models" - tags: ClassVar[list[str]] = ["Import"] + tags = ("Import",) @post( "/{model_name:str}/import/preview", @@ -751,8 +751,7 @@ def _build_import_response( success = False else: message = ( - f"Import completed with partial success: " - f"{imported_count} rows imported, {failed_count} rows failed" + f"Import completed with partial success: {imported_count} rows imported, {failed_count} rows failed" ) success = True @@ -792,7 +791,7 @@ def _get_view_class( if not registry.has_model_by_name(model_name): msg = f"Model '{model_name}' not found" raise NotFoundException(msg) - return registry.get_view_by_name(model_name) + return registry.get_model_view_by_name(model_name) @staticmethod async def _read_file_with_encoding(upload_file: UploadFile) -> tuple[str, str]: @@ -848,7 +847,7 @@ def _detect_delimiter(content: str) -> str: except csv.Error: # Fallback: count occurrences of each delimiter delimiter_counts = {d: sample.count(d) for d in SUPPORTED_DELIMITERS} - return max(delimiter_counts, key=delimiter_counts.get) # type: ignore[arg-type] + return max(delimiter_counts, key=delimiter_counts.get) # ty: ignore[no-matching-overload] @staticmethod def _parse_csv(content: str, delimiter: str) -> tuple[list[list[str]], list[str], int]: diff --git a/src/litestar_admin/controllers/models.py b/src/litestar_admin/controllers/models.py index bebd6ee..71a14c3 100644 --- a/src/litestar_admin/controllers/models.py +++ b/src/litestar_admin/controllers/models.py @@ -2,8 +2,9 @@ from __future__ import annotations +import contextlib from dataclasses import dataclass -from typing import Any, ClassVar +from typing import Any from litestar import Controller, Request, delete, get, patch, post, put from litestar.exceptions import NotFoundException @@ -143,7 +144,7 @@ class ModelsController(Controller): """ path = "/api/models" - tags: ClassVar[list[str]] = ["Models"] + tags = ("Models",) @get( "/", @@ -222,7 +223,7 @@ async def list_records( sort_order = "asc" try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -276,7 +277,7 @@ async def create_record( NotFoundException: If the model is not registered. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -327,7 +328,7 @@ async def get_schema( NotFoundException: If the model is not registered. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -363,7 +364,7 @@ async def get_record( NotFoundException: If the model or record is not found. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -409,9 +410,8 @@ async def update_record_full( Raises: NotFoundException: If the model or record is not found. """ - print(f"[UPDATE] PUT request for {model_name}/{record_id} with data: {data}") try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -473,7 +473,7 @@ async def update_record_partial( NotFoundException: If the model or record is not found. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -536,7 +536,7 @@ async def delete_record( NotFoundException: If the model or record is not found. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc @@ -586,10 +586,10 @@ async def _log_audit( from litestar_admin.audit.models import AuditLog audit_logger = logging.getLogger("litestar_admin.audit") - audit_logger.info(f"Audit log: {action.value} on {model_name} record {record_id}") + audit_logger.info("Audit log: %s on %s record %s", action.value, model_name, record_id) try: - print(f"[AUDIT] Starting audit log for {action.value} on {model_name} record {record_id}") + audit_logger.debug("Starting audit log for %s on %s record %s", action.value, model_name, record_id) entry = await audit_admin_action( connection=request, @@ -599,7 +599,7 @@ async def _log_audit( changes=changes, metadata=metadata, ) - print(f"[AUDIT] Created audit entry: {entry.id}, actor: {entry.actor_email}") + audit_logger.debug("Created audit entry: %s, actor: %s", entry.id, entry.actor_email) # Create the AuditLog model directly and add to session audit_log = AuditLog( @@ -616,21 +616,14 @@ async def _log_audit( user_agent=entry.user_agent, ) - print(f"[AUDIT] Session state before add: in_transaction={db_session.in_transaction()}") db_session.add(audit_log) - print("[AUDIT] Added to session, flushing...") await db_session.flush() - print("[AUDIT] Flushed, committing...") await db_session.commit() - print("[AUDIT] Committed successfully!") audit_logger.info("Audit entry committed successfully") - except Exception as e: - print(f"[AUDIT] ERROR: {type(e).__name__}: {e}") - audit_logger.error(f"Audit logging failed: {e}", exc_info=True) - try: + except Exception: + audit_logger.exception("Audit logging failed") + with contextlib.suppress(Exception): await db_session.rollback() - except Exception: - pass def _convert_pk(pk_str: str, service: AdminService[Any]) -> Any: diff --git a/src/litestar_admin/controllers/oauth.py b/src/litestar_admin/controllers/oauth.py index c0eaae3..c2352f1 100644 --- a/src/litestar_admin/controllers/oauth.py +++ b/src/litestar_admin/controllers/oauth.py @@ -3,10 +3,10 @@ from __future__ import annotations import secrets -from typing import Any, ClassVar +from typing import Any from litestar import Controller, get -from litestar.connection import ASGIConnection +from litestar.connection import ASGIConnection # noqa: TC002 from litestar.exceptions import NotAuthorizedException, NotFoundException from litestar.response import Redirect from litestar.status_codes import HTTP_200_OK @@ -29,7 +29,7 @@ class OAuthController(Controller): """ path = "/auth/oauth" - tags: ClassVar[list[str]] = ["OAuth Authentication"] + tags = ("OAuth Authentication",) @get( "/{provider:str}/login", @@ -150,7 +150,7 @@ async def oauth_callback( state_value = request.query_params.get("state") # Handle the callback - user, tokens = await admin_config.auth_backend.handle_callback( + user, _tokens = await admin_config.auth_backend.handle_callback( provider_name=provider, code=code, state=state_value, diff --git a/src/litestar_admin/controllers/relationships.py b/src/litestar_admin/controllers/relationships.py index de0b40a..f248e68 100644 --- a/src/litestar_admin/controllers/relationships.py +++ b/src/litestar_admin/controllers/relationships.py @@ -5,7 +5,7 @@ import contextlib import logging from dataclasses import dataclass, field -from typing import Any, ClassVar +from typing import Any from litestar import Controller, get from litestar.exceptions import NotFoundException @@ -155,7 +155,7 @@ class RelationshipsController(Controller): """ path = "/api/models/{model_name:str}/relationships/{field_name:str}" - tags: ClassVar[list[str]] = ["Relationships"] + tags = ("Relationships",) @get( "/search", @@ -360,7 +360,7 @@ def _get_view_and_relationship( NotFoundException: If the model or relationship is not found. """ try: - view_class = admin_registry.get_view_by_name(model_name) + view_class = admin_registry.get_model_view_by_name(model_name) except KeyError as exc: raise NotFoundException(f"Model '{model_name}' not found") from exc diff --git a/src/litestar_admin/controllers/settings.py b/src/litestar_admin/controllers/settings.py index 473be0b..7a06eef 100644 --- a/src/litestar_admin/controllers/settings.py +++ b/src/litestar_admin/controllers/settings.py @@ -17,7 +17,7 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import Any, ClassVar +from typing import Any from litestar import Controller, delete, get, post, put from litestar.exceptions import NotFoundException @@ -144,7 +144,7 @@ class SettingsController(Controller): """ path = "/api/settings" - tags: ClassVar[list[str]] = ["Settings"] + tags = ("Settings",) @get( "/", diff --git a/src/litestar_admin/controllers/users.py b/src/litestar_admin/controllers/users.py index 8beff8a..ad285c6 100644 --- a/src/litestar_admin/controllers/users.py +++ b/src/litestar_admin/controllers/users.py @@ -5,7 +5,7 @@ import contextlib import logging from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from litestar_admin.auth.password_reset import PasswordResetService @@ -383,7 +383,7 @@ class UserManagementController(Controller): """ path = "/api/users" - tags: ClassVar[list[str]] = ["User Management"] + tags = ("User Management",) @get( "/", diff --git a/src/litestar_admin/fields/rich_text.py b/src/litestar_admin/fields/rich_text.py index fa8a0a2..a80db38 100644 --- a/src/litestar_admin/fields/rich_text.py +++ b/src/litestar_admin/fields/rich_text.py @@ -279,11 +279,7 @@ def validate_rich_text_field( return errors # Check max length on plain text - if ( - plain_text is not None - and field_config.max_length is not None - and not field_config.is_length_valid(plain_text) - ): + if plain_text is not None and field_config.max_length is not None and not field_config.is_length_valid(plain_text): errors.append( RichTextFieldValidationError( field_name=field_config.name, diff --git a/src/litestar_admin/fields/sanitize.py b/src/litestar_admin/fields/sanitize.py index bc89bfa..f5954b7 100644 --- a/src/litestar_admin/fields/sanitize.py +++ b/src/litestar_admin/fields/sanitize.py @@ -86,13 +86,15 @@ } # URL schemes that are safe for href and src attributes -SAFE_URL_SCHEMES: frozenset[str] = frozenset({ - "http", - "https", - "mailto", - "tel", - "data", # For base64 embedded images -}) +SAFE_URL_SCHEMES: frozenset[str] = frozenset( + { + "http", + "https", + "mailto", + "tel", + "data", # For base64 embedded images + } +) def sanitize_html( diff --git a/src/litestar_admin/middleware/auth.py b/src/litestar_admin/middleware/auth.py index 1c8067c..59174b0 100644 --- a/src/litestar_admin/middleware/auth.py +++ b/src/litestar_admin/middleware/auth.py @@ -79,15 +79,19 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: @staticmethod async def _send_not_found(send: Send) -> None: """Send a plain 404 response to avoid leaking admin panel existence.""" - await send({ - "type": "http.response.start", - "status": 404, - "headers": [(b"content-type", b"text/plain")], - }) - await send({ - "type": "http.response.body", - "body": b"Not Found", - }) + await send( + { + "type": "http.response.start", + "status": 404, + "headers": [(b"content-type", b"text/plain")], + } + ) + await send( + { + "type": "http.response.body", + "body": b"Not Found", + } + ) async def _get_user(self, scope: Scope) -> Any | None: """Try to authenticate via Bearer token first, then fall back to session.""" diff --git a/src/litestar_admin/middleware/ratelimit.py b/src/litestar_admin/middleware/ratelimit.py index ef11cf1..6cd2825 100644 --- a/src/litestar_admin/middleware/ratelimit.py +++ b/src/litestar_admin/middleware/ratelimit.py @@ -23,8 +23,9 @@ import time from collections import defaultdict from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, ClassVar, Protocol, cast, runtime_checkable +from typing import TYPE_CHECKING, Any, Protocol, cast, runtime_checkable +from litestar.enums import ScopeType from litestar.middleware import AbstractMiddleware from litestar.status_codes import HTTP_429_TOO_MANY_REQUESTS @@ -544,7 +545,7 @@ class RateLimitMiddleware(AbstractMiddleware): ) """ - scopes: ClassVar[set[str]] = {"http"} + scopes = {ScopeType.HTTP} # noqa: RUF012 def __init__( self, diff --git a/src/litestar_admin/plugin.py b/src/litestar_admin/plugin.py index 49cae72..dd6001d 100644 --- a/src/litestar_admin/plugin.py +++ b/src/litestar_admin/plugin.py @@ -17,6 +17,7 @@ from litestar import Litestar, Router from litestar.config.app import AppConfig from litestar.di import Provide + from litestar.handlers import HTTPRouteHandler __all__ = ["AdminPlugin"] @@ -227,12 +228,6 @@ def _configure_static_files(self, app_config: AppConfig) -> None: return index_html_path = static_path / "index.html" - models_html_path = static_path / "models" / "index.html" - actions_html_path = static_path / "actions" / "index.html" - pages_html_path = static_path / "pages" / "index.html" - custom_html_path = static_path / "custom" / "index.html" - embeds_html_path = static_path / "embeds" / "index.html" - users_html_path = static_path / "users" / "index.html" # Create static router for actual static files (_next/*, login/, etc.) static_router = create_static_files_router( @@ -243,122 +238,46 @@ def _configure_static_files(self, app_config: AppConfig) -> None: after_request=_add_cache_headers, ) - # SPA catch-all route - serves appropriate index.html for SPA routes - # This enables client-side routing for paths like /admin/models/User - # IMPORTANT: We only handle routes that are NOT static assets - @get( - path=[ - f"{self._config.base_url}/models/", - f"{self._config.base_url}/models/{{path:path}}", - ], - name="admin_spa_models_fallback", - include_in_schema=False, - ) - async def spa_models_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve models/index.html for SPA client-side routing.""" - html_path = models_html_path if models_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() - return Response( - content=content, - media_type="text/html", - headers={"Cache-Control": "no-cache, no-store, must-revalidate"}, - ) - return Response(content=b"Not Found", status_code=404) + # SPA catch-all routes - serve each section's index.html for client-side + # routing (e.g. /admin/models/User). IMPORTANT: these only handle routes + # that are NOT static assets. + spa_sections = ("models", "actions", "pages", "custom", "embeds", "users") + spa_fallbacks = [ + self._make_spa_fallback(section, static_path / section / "index.html", index_html_path) + for section in spa_sections + ] - @get( - path=[ - f"{self._config.base_url}/actions/", - f"{self._config.base_url}/actions/{{path:path}}", - ], - name="admin_spa_actions_fallback", - include_in_schema=False, - ) - async def spa_actions_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve actions/index.html for SPA client-side routing.""" - html_path = actions_html_path if actions_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() - return Response( - content=content, - media_type="text/html", - headers={"Cache-Control": "no-cache, no-store, must-revalidate"}, - ) - return Response(content=b"Not Found", status_code=404) + app_config.route_handlers = [ + *list(app_config.route_handlers or []), + static_router, + *spa_fallbacks, + ] - @get( - path=[ - f"{self._config.base_url}/pages/", - f"{self._config.base_url}/pages/{{path:path}}", - ], - name="admin_spa_pages_fallback", - include_in_schema=False, - ) - async def spa_pages_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve pages/index.html for SPA client-side routing.""" - html_path = pages_html_path if pages_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() - return Response( - content=content, - media_type="text/html", - headers={"Cache-Control": "no-cache, no-store, must-revalidate"}, - ) - return Response(content=b"Not Found", status_code=404) + def _make_spa_fallback(self, section: str, html_path: Path, index_html_path: Path) -> HTTPRouteHandler: + """Build a SPA catch-all route handler for one admin section. - @get( - path=[ - f"{self._config.base_url}/custom/", - f"{self._config.base_url}/custom/{{path:path}}", - ], - name="admin_spa_custom_fallback", - include_in_schema=False, - ) - async def spa_custom_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve custom/index.html for SPA client-side routing.""" - html_path = custom_html_path if custom_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() - return Response( - content=content, - media_type="text/html", - headers={"Cache-Control": "no-cache, no-store, must-revalidate"}, - ) - return Response(content=b"Not Found", status_code=404) + Args: + section: The admin section name (e.g. "models"). + html_path: The section's own index.html, if the frontend built one. + index_html_path: The top-level index.html fallback. - @get( - path=[ - f"{self._config.base_url}/embeds/", - f"{self._config.base_url}/embeds/{{path:path}}", - ], - name="admin_spa_embeds_fallback", - include_in_schema=False, - ) - async def spa_embeds_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve embeds/index.html for SPA client-side routing.""" - html_path = embeds_html_path if embeds_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() - return Response( - content=content, - media_type="text/html", - headers={"Cache-Control": "no-cache, no-store, must-revalidate"}, - ) - return Response(content=b"Not Found", status_code=404) + Returns: + A Litestar route handler serving the section's SPA entry point. + """ @get( path=[ - f"{self._config.base_url}/users/", - f"{self._config.base_url}/users/{{path:path}}", + f"{self._config.base_url}/{section}/", + f"{self._config.base_url}/{section}/{{path:path}}", ], - name="admin_spa_users_fallback", + name=f"admin_spa_{section}_fallback", include_in_schema=False, ) - async def spa_users_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 - """Serve users/index.html for SPA client-side routing.""" - html_path = users_html_path if users_html_path.exists() else index_html_path - if html_path.exists(): - content = html_path.read_bytes() + async def _spa_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 + """Serve a section's index.html for SPA client-side routing.""" + resolved_path = html_path if html_path.exists() else index_html_path + if resolved_path.exists(): + content = resolved_path.read_bytes() return Response( content=content, media_type="text/html", @@ -366,16 +285,7 @@ async def spa_users_fallback(path: str = "") -> Response[bytes]: # noqa: ARG001 ) return Response(content=b"Not Found", status_code=404) - app_config.route_handlers = [ - *list(app_config.route_handlers or []), - static_router, - spa_models_fallback, - spa_actions_fallback, - spa_pages_fallback, - spa_custom_fallback, - spa_embeds_fallback, - spa_users_fallback, - ] + return _spa_fallback async def _startup(self, app: Litestar) -> None: """Run startup tasks for the admin plugin. diff --git a/src/litestar_admin/registry.py b/src/litestar_admin/registry.py index 86eb84d..25c88b5 100644 --- a/src/litestar_admin/registry.py +++ b/src/litestar_admin/registry.py @@ -106,7 +106,9 @@ def unregister(self, model_or_identity: type[Any] | str) -> None: view_class = self._views_by_identity.pop(identity) # Also remove from model mapping if it's a model view - if hasattr(view_class, "model") and view_class.model in self._views_by_model: + from litestar_admin.views import BaseModelView as _BaseModelView + + if issubclass(view_class, _BaseModelView) and view_class.model in self._views_by_model: del self._views_by_model[view_class.model] else: # Unregister by model (backward compatibility for model views) @@ -157,6 +159,30 @@ def get_view_by_name(self, name: str) -> type[BaseAdminView]: raise KeyError(msg) return self._views_by_identity[identity] + def get_model_view_by_name(self, name: str) -> type[BaseModelView]: + """Get a model view class by identity (URL-safe name). + + Like `get_view_by_name`, but narrows the result to model views only, + for callers (e.g. CRUD controllers) that require model-specific + attributes such as `model` or `get_list_columns`. + + Args: + name: The view identity to look up (case-insensitive). + + Returns: + The registered model view class with the given identity. + + Raises: + KeyError: If the identity is not registered or is not a model view. + """ + from litestar_admin.views import BaseModelView as _BaseModelView + + view_class = self.get_view_by_name(name) + if not issubclass(view_class, _BaseModelView): + msg = f"View '{name}' is not a model view" + raise KeyError(msg) + return view_class + def has_view(self, identity: str) -> bool: """Check if a view identity is registered. @@ -210,7 +236,9 @@ def list_model_views(self) -> list[type[BaseModelView]]: Returns: List of ModelView/BaseModelView classes. """ - return [view for view in self._views_by_identity.values() if view.view_type == "model"] + from litestar_admin.views import BaseModelView as _BaseModelView + + return [view for view in self._views_by_identity.values() if issubclass(view, _BaseModelView)] def list_custom_views(self) -> list[type[BaseAdminView]]: """List only custom (non-model) data views. @@ -260,6 +288,8 @@ def list_models(self) -> list[dict[str, Any]]: Returns: List of dictionaries containing model view metadata. """ + from litestar_admin.views import BaseModelView as _BaseModelView + return [ { "name": view_class.name, @@ -272,7 +302,7 @@ def list_models(self) -> list[dict[str, Any]]: "can_view_details": view_class.can_view_details, } for view_class in self._views_by_identity.values() - if view_class.view_type == "model" + if issubclass(view_class, _BaseModelView) ] def get_navigation(self) -> dict[str, list[dict[str, Any]]]: diff --git a/src/litestar_admin/service.py b/src/litestar_admin/service.py index 6339263..54b12b6 100644 --- a/src/litestar_admin/service.py +++ b/src/litestar_admin/service.py @@ -22,7 +22,7 @@ from litestar.connection import ASGIConnection from sqlalchemy.ext.asyncio import AsyncSession - from sqlalchemy.schema import Column + from sqlalchemy.orm import Mapper from sqlalchemy.sql import ColumnElement from litestar_admin.views import BaseModelView @@ -97,7 +97,22 @@ def model(self) -> type[T]: """Return the model class.""" return self._view_class.model - def _get_primary_key_column(self) -> Column[Any]: + def _get_mapper(self) -> Mapper[Any]: + """Get the SQLAlchemy mapper for the model. + + Returns: + The SQLAlchemy Mapper for the service's model. + + Raises: + ValueError: If the model is not a mapped SQLAlchemy class. + """ + mapper = inspect(self.model) + if mapper is None: + msg = f"Could not inspect model {self.model.__name__}: not a mapped SQLAlchemy class" + raise ValueError(msg) + return mapper + + def _get_primary_key_column(self) -> ColumnElement[Any]: """Get the primary key column for the model. Returns: @@ -106,7 +121,7 @@ def _get_primary_key_column(self) -> Column[Any]: Raises: ValueError: If no primary key is found. """ - mapper = inspect(self.model) + mapper = self._get_mapper() pk_columns = mapper.primary_key if not pk_columns: msg = f"Model {self.model.__name__} has no primary key" @@ -441,7 +456,7 @@ async def create_record( ) # Coerce values to proper Python types - mapper = inspect(self.model) + mapper = self._get_mapper() column_map = {c.name: c for c in mapper.columns} coerced_data = {} for key, value in processed_data.items(): @@ -502,7 +517,7 @@ async def update_record( ) # Get column mapping for value coercion - mapper = inspect(self.model) + mapper = self._get_mapper() column_map = {c.name: c for c in mapper.columns} # Apply updates @@ -583,7 +598,7 @@ def _apply_full_update(self, record: T, data: dict[str, Any]) -> None: record: The record to update. data: The data to apply. """ - mapper = inspect(self.model) + mapper = self._get_mapper() for column in mapper.columns: column_name = column.name @@ -612,8 +627,7 @@ async def delete_record(self, pk: Any, *, soft_delete: bool = False) -> bool: return False if soft_delete and hasattr(record, "deleted_at"): - # Soft delete: set deleted_at timestamp - record.deleted_at = datetime.now(tz=timezone.utc) # type: ignore[attr-defined] + record.deleted_at = datetime.now(tz=timezone.utc) # ty: ignore[invalid-assignment] await self._session.flush() else: # Hard delete @@ -668,7 +682,7 @@ async def bulk_delete( for record in records: if soft_delete and hasattr(record, "deleted_at"): - record.deleted_at = datetime.now(tz=timezone.utc) # type: ignore[attr-defined] + record.deleted_at = datetime.now(tz=timezone.utc) # ty: ignore[invalid-assignment] else: await self._session.delete(record) deleted_count += 1 @@ -702,7 +716,7 @@ def get_model_schema(self, *, is_create: bool = True) -> dict[str, Any]: Returns: Dictionary representing the JSON schema. """ - mapper = inspect(self.model) + mapper = self._get_mapper() properties: dict[str, Any] = {} required: list[str] = [] @@ -801,7 +815,7 @@ def _get_fk_relationship_map(self) -> dict[str, dict[str, Any]]: Dictionary mapping FK column names to relationship details. """ fk_map: dict[str, dict[str, Any]] = {} - mapper = inspect(self.model) + mapper = self._get_mapper() # Check for explicit relationship configurations from the view for rel_info in self._view_class.relationship_fields(): @@ -848,21 +862,59 @@ def _column_to_schema(self, column: Any) -> dict[str, Any]: type_info = _SQLALCHEMY_TYPE_MAP.get(type_name, {"type": "string"}) schema.update(type_info) - # Handle Enum types - extract enum values for dropdown - if type_name == "ENUM" and hasattr(column.type, "enums"): - schema["type"] = "string" - # Get enum values (handles both native SQL enums and Python enum classes) - enum_values = column.type.enums - if hasattr(column.type, "enum_class") and column.type.enum_class: - # Python Enum class - extract values - enum_values = [e.value for e in column.type.enum_class] - schema["enum"] = list(enum_values) + self._apply_enum_schema(schema, column, type_name) # Add maxLength for string types with length if type_name in ("STRING", "VARCHAR", "CHAR") and hasattr(column.type, "length") and column.type.length: schema["maxLength"] = column.type.length - # Add format for common field names + self._apply_format_schema(schema, column) + + # Add nullable info using JSON schema pattern + if column.nullable: + current_type = schema.get("type") + if current_type: + schema["type"] = [current_type, "null"] + + # Add primary key info + if column.primary_key: + schema["readOnly"] = True + + self._apply_default_schema(schema, column) + + # Add description from column doc if available + if column.doc: + schema["description"] = column.doc + + return schema + + @staticmethod + def _apply_enum_schema(schema: dict[str, Any], column: Any, type_name: str) -> None: + """Add enum values to the schema for ENUM columns, in place. + + Args: + schema: The schema dict being built, mutated in place. + column: The SQLAlchemy column. + type_name: The uppercased SQLAlchemy type name. + """ + if type_name != "ENUM" or not hasattr(column.type, "enums"): + return + schema["type"] = "string" + # Get enum values (handles both native SQL enums and Python enum classes) + enum_values = column.type.enums + if hasattr(column.type, "enum_class") and column.type.enum_class: + # Python Enum class - extract values + enum_values = [e.value for e in column.type.enum_class] + schema["enum"] = list(enum_values) + + @staticmethod + def _apply_format_schema(schema: dict[str, Any], column: Any) -> None: + """Add a JSON schema `format` hint based on common field names, in place. + + Args: + schema: The schema dict being built, mutated in place. + column: The SQLAlchemy column. + """ column_lower = column.name.lower() if column_lower in ("email", "email_address", "user_email"): schema["format"] = "email" @@ -881,29 +933,19 @@ def _column_to_schema(self, column: Any) -> dict[str, Any]: ): schema["format"] = "textarea" - # Add nullable info using JSON schema pattern - if column.nullable: - current_type = schema.get("type") - if current_type: - schema["type"] = [current_type, "null"] + @staticmethod + def _apply_default_schema(schema: dict[str, Any], column: Any) -> None: + """Add the column's Python-side default value to the schema, in place. - # Add primary key info - if column.primary_key: - schema["readOnly"] = True - - # Add default value if present (Python-side default) - if column.default is not None: - default_arg = column.default.arg - # Handle callable defaults (skip them) vs literal values - if not callable(default_arg): - # Handle enum defaults - if hasattr(default_arg, "value"): - schema["default"] = default_arg.value - else: - schema["default"] = default_arg - - # Add description from column doc if available - if column.doc: - schema["description"] = column.doc - - return schema + Args: + schema: The schema dict being built, mutated in place. + column: The SQLAlchemy column. + """ + if column.default is None: + return + default_arg = column.default.arg + # Handle callable defaults (skip them) vs literal values + if callable(default_arg): + return + # Handle enum defaults + schema["default"] = default_arg.value if hasattr(default_arg, "value") else default_arg diff --git a/src/litestar_admin/settings/models.py b/src/litestar_admin/settings/models.py index 205a138..16abd04 100644 --- a/src/litestar_admin/settings/models.py +++ b/src/litestar_admin/settings/models.py @@ -23,14 +23,26 @@ async def create_setting(session: AsyncSession) -> None: from __future__ import annotations +import sys from datetime import datetime, timezone -from enum import StrEnum from typing import Any from sqlalchemy import Boolean, DateTime, Index, String, Text from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy.types import JSON +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + from enum import Enum + + class StrEnum(str, Enum): + """Backport of `enum.StrEnum` for Python < 3.11.""" + + def __str__(self) -> str: + return str(self.value) + + __all__ = ["AdminSettings", "AdminSettingsBase", "SettingsCategory"] diff --git a/src/litestar_admin/views/base.py b/src/litestar_admin/views/base.py index af82d9e..2b94f2c 100644 --- a/src/litestar_admin/views/base.py +++ b/src/litestar_admin/views/base.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, Literal from litestar_admin.relationships import RelationshipDetector, get_relationship_detector from litestar_admin.views.admin_view import BaseAdminView @@ -63,7 +63,7 @@ class UserAdmin(BaseModelView): name_plural: ClassVar[str] = "" icon: ClassVar[str] = "table" category: ClassVar[str | None] = None - view_type: ClassVar[str] = "model" # Override from BaseAdminView + view_type: ClassVar[Literal["model"]] = "model" # Override from BaseAdminView # Column configuration column_list: ClassVar[list[str]] = [] diff --git a/src/litestar_admin/views/custom.py b/src/litestar_admin/views/custom.py index bbf507a..ff16ef8 100644 --- a/src/litestar_admin/views/custom.py +++ b/src/litestar_admin/views/custom.py @@ -213,7 +213,7 @@ def __init_subclass__(cls, **kwargs: Any) -> None: msg = f"Column must be a dict or ColumnDefinition, got {type(col)}" raise TypeError(msg) # Update to normalized list (type: ignore needed as we're changing the type) - cls.columns = normalized # type: ignore[assignment] + cls.columns = normalized # ty: ignore[invalid-assignment] @abstractmethod async def get_list( diff --git a/tests/test_auth_controller.py b/tests/test_auth_controller.py index 5dd5a9d..8b1d2c2 100644 --- a/tests/test_auth_controller.py +++ b/tests/test_auth_controller.py @@ -468,4 +468,4 @@ def test_controller_path(self) -> None: def test_controller_tags(self) -> None: """Test controller tags for OpenAPI.""" - assert AuthController.tags == ["Authentication"] + assert AuthController.tags == ("Authentication",) diff --git a/tests/test_permissions_integration.py b/tests/test_permissions_integration.py index 0f0f731..195d8e0 100644 --- a/tests/test_permissions_integration.py +++ b/tests/test_permissions_integration.py @@ -18,15 +18,14 @@ from litestar.middleware.base import AbstractMiddleware from litestar.testing import AsyncTestClient from litestar.types import Receive, Scope, Send +from litestar_permissions import PermissionsConfig, require_permission, require_role +from litestar_permissions.models import create_models +from litestar_permissions.resolver import PermissionResolver from sqlalchemy import String, Uuid from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from sqlalchemy.pool import StaticPool -from litestar_permissions import PermissionsConfig, require_permission, require_role -from litestar_permissions.models import create_models -from litestar_permissions.resolver import PermissionResolver - # --------------------------------------------------------------------------- # ORM Base + RBAC models (created once at module level) @@ -211,12 +210,14 @@ async def seed_data() -> dict[str, str]: await session.flush() # Role -> Permission links - session.add_all([ - RolePermission(role_id=reader_role.id, permission_id=perm_read.id), - RolePermission(role_id=writer_role.id, permission_id=perm_write.id), - RolePermission(role_id=admin_role.id, permission_id=perm_read.id), - RolePermission(role_id=admin_role.id, permission_id=perm_write.id), - ]) + session.add_all( + [ + RolePermission(role_id=reader_role.id, permission_id=perm_read.id), + RolePermission(role_id=writer_role.id, permission_id=perm_write.id), + RolePermission(role_id=admin_role.id, permission_id=perm_read.id), + RolePermission(role_id=admin_role.id, permission_id=perm_write.id), + ] + ) # User -> Role assignments session.add(UserRoleAssignment(user_id=regular_user.id, role_id=reader_role.id)) diff --git a/tests/test_registry.py b/tests/test_registry.py index 6c5be00..82f0833 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -36,7 +36,7 @@ class UserAdmin2(ModelView, model=user_model): registry.register(UserAdmin1) with pytest.raises( - ValueError, match="(Model User is already registered|View identity 'user' is already registered)" + ValueError, match=r"(Model User is already registered|View identity 'user' is already registered)" ): registry.register(UserAdmin2) diff --git a/tests/test_rich_text_sanitize.py b/tests/test_rich_text_sanitize.py index 7aebf57..ac94d10 100644 --- a/tests/test_rich_text_sanitize.py +++ b/tests/test_rich_text_sanitize.py @@ -70,7 +70,7 @@ def test_removes_embed_tags(self) -> None: def test_removes_onclick_attributes(self) -> None: """Test that onclick event handlers are removed.""" - content = '

Click me

' + content = "

Click me

" result = sanitize_html(content, allowed_tags=["p"]) assert "onclick" not in result assert "

Click me

" in result @@ -83,13 +83,13 @@ def test_removes_onerror_attributes(self) -> None: def test_removes_onload_attributes(self) -> None: """Test that onload event handlers are removed.""" - content = '

Text

' + content = "

Text

" result = sanitize_html(content, allowed_tags=["p"]) assert "onload" not in result def test_removes_javascript_href(self) -> None: """Test that javascript: protocol in href is handled.""" - content = 'Click' + content = "Click" result = sanitize_html(content, allowed_tags=["a"]) assert "javascript:" not in result