Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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: |
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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"
Expand Down
5 changes: 3 additions & 2 deletions src/litestar_admin/audit/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down
10 changes: 8 additions & 2 deletions src/litestar_admin/auth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
15 changes: 9 additions & 6 deletions src/litestar_admin/auth/password.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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:
Expand Down
87 changes: 43 additions & 44 deletions src/litestar_admin/contrib/providers/in_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,54 @@

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

__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.

Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/litestar_admin/controllers/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -139,7 +139,7 @@ class AuthController(Controller):
"""

path = "/api/auth"
tags: ClassVar[list[str]] = ["Authentication"]
tags = ("Authentication",)

@post(
"/login",
Expand Down
6 changes: 3 additions & 3 deletions src/litestar_admin/controllers/bulk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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)
40 changes: 19 additions & 21 deletions src/litestar_admin/controllers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -84,7 +83,7 @@ class ConfigController(Controller):
"""

path = "/api/config"
tags: ClassVar[list[str]] = ["Configuration"]
tags = ("Configuration",)

@get(
"/",
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading