feat: add Authentik access widgets
This commit is contained in:
@@ -1,9 +1,7 @@
|
||||
"""Authentik directory API client.
|
||||
"""Read-only Authentik directory client.
|
||||
|
||||
Authentik is the user-directory source (replacing the Jellyfin-backed Users
|
||||
page). This client wraps the Authentik REST API for browsing the user directory
|
||||
with pagination and search. OIDC authentication is unchanged — this client is
|
||||
for the directory, not SSO.
|
||||
The client normalizes the subset of Authentik core data that Manage displays.
|
||||
It deliberately does not fetch individual users or expose policy/provider data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,9 +15,34 @@ from media_library_viewer_api.clients.http_timeout import DEFAULT_READ_TIMEOUT,
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MAX_COLLECTION_ITEMS = 10_000
|
||||
_PAGE_SIZE = 100
|
||||
|
||||
|
||||
def _text(value: Any) -> str:
|
||||
return str(value).strip() if value is not None else ""
|
||||
|
||||
|
||||
def _identifier(item: dict[str, Any]) -> str:
|
||||
for key in ("pk", "id", "uuid"):
|
||||
value = _text(item.get(key))
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _page_total(payload: dict[str, Any], fallback: int) -> int:
|
||||
pagination = payload.get("pagination")
|
||||
if isinstance(pagination, dict):
|
||||
try:
|
||||
return max(0, int(pagination.get("count") or fallback))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return fallback
|
||||
|
||||
|
||||
class AuthentikClient:
|
||||
"""Small wrapper around the Authentik core directory API."""
|
||||
"""Small wrapper around Authentik's read-only core API."""
|
||||
|
||||
def __init__(self, base_url: str, api_token: str, timeout: float = DEFAULT_READ_TIMEOUT):
|
||||
if not base_url:
|
||||
@@ -31,88 +54,139 @@ class AuthentikClient:
|
||||
if self.base_url.endswith("/api/v3"):
|
||||
self.base_url = self.base_url[:-7]
|
||||
self.api_token = api_token
|
||||
# timeout is the per-response READ timeout (seconds); connect timeout is fixed at 5s.
|
||||
self.timeout = http_timeout(timeout)
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update(
|
||||
{
|
||||
"Authorization": f"Bearer {api_token}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
)
|
||||
self.session.headers.update({"Authorization": f"Bearer {api_token}", "Accept": "application/json"})
|
||||
|
||||
def get(self, path: str, **params: Any) -> Any:
|
||||
"""GET an Authentik endpoint and include useful response text on errors."""
|
||||
clean_params = {k: v for k, v in params.items() if v is not None and v != ""}
|
||||
clean_params = {key: value for key, value in params.items() if value is not None and value != ""}
|
||||
logger.debug("Authentik GET %s params=%s", path, sorted(clean_params.keys()))
|
||||
response = self.session.get(
|
||||
f"{self.base_url}/api/v3{path}",
|
||||
params=clean_params,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
response = self.session.get(f"{self.base_url}/api/v3{path}", params=clean_params, timeout=self.timeout)
|
||||
try:
|
||||
response.raise_for_status()
|
||||
except requests.HTTPError as exc:
|
||||
detail = response.text[:500]
|
||||
logger.warning(
|
||||
"Authentik GET %s failed status=%s url=%s",
|
||||
path,
|
||||
response.status_code,
|
||||
response.url,
|
||||
)
|
||||
raise requests.HTTPError(
|
||||
f"{response.status_code} for {response.url}: {detail}",
|
||||
response=response,
|
||||
) from exc
|
||||
logger.debug("Authentik GET %s ok status=%s", path, response.status_code)
|
||||
logger.warning("Authentik GET %s failed status=%s url=%s", path, response.status_code, response.url)
|
||||
raise requests.HTTPError(f"{response.status_code} for {response.url}: {detail}", response=response) from exc
|
||||
return response.json()
|
||||
|
||||
def users(
|
||||
def users(self, search: str | None = None, page: int = 1, page_size: int = 50) -> dict[str, Any]:
|
||||
"""Return one raw user page for the directory and messaging surfaces."""
|
||||
payload = self.get("/core/users/", search=search, page=page, page_size=page_size)
|
||||
if not isinstance(payload, dict):
|
||||
logger.warning("Authentik users payload was not a dict: %s", type(payload).__name__)
|
||||
return {"items": [], "total": 0, "page": page, "page_size": page_size}
|
||||
results = payload.get("results")
|
||||
items = [item for item in results if isinstance(item, dict)] if isinstance(results, list) else []
|
||||
return {"items": items, "total": _page_total(payload, len(items)), "page": page, "page_size": page_size}
|
||||
|
||||
def _collection(self, path: str, limit: int = _MAX_COLLECTION_ITEMS) -> dict[str, Any]:
|
||||
"""Read a paginated core collection with a hard cap and loop protection."""
|
||||
try:
|
||||
requested = max(1, min(int(limit), _MAX_COLLECTION_ITEMS))
|
||||
except (TypeError, ValueError):
|
||||
requested = _MAX_COLLECTION_ITEMS
|
||||
items: list[dict[str, Any]] = []
|
||||
page = 1
|
||||
total = 0
|
||||
while len(items) < requested:
|
||||
payload = self.get(path, page=page, page_size=min(_PAGE_SIZE, requested - len(items)))
|
||||
if not isinstance(payload, dict):
|
||||
logger.warning("Authentik %s payload was not a dict: %s", path, type(payload).__name__)
|
||||
break
|
||||
results = payload.get("results")
|
||||
page_items = [item for item in results if isinstance(item, dict)] if isinstance(results, list) else []
|
||||
total = _page_total(payload, len(items) + len(page_items))
|
||||
items.extend(page_items[: requested - len(items)])
|
||||
if not page_items or len(items) >= total:
|
||||
break
|
||||
page += 1
|
||||
if page > 100: # defensive limit for malformed pagination responses
|
||||
logger.warning("Authentik %s pagination stopped after 100 pages", path)
|
||||
break
|
||||
return {"items": items, "total": total or len(items)}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_group(item: dict[str, Any]) -> dict[str, str] | None:
|
||||
group_id = _identifier(item)
|
||||
if not group_id:
|
||||
return None
|
||||
name = _text(item.get("name") or item.get("display_name") or item.get("slug"))
|
||||
return {"id": group_id, "name": name or f"Unnamed group ({group_id})"}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_application(item: dict[str, Any]) -> dict[str, str]:
|
||||
app_id = _identifier(item)
|
||||
return {
|
||||
"id": app_id,
|
||||
"name": _text(item.get("name") or item.get("slug") or item.get("meta_name")) or "Unnamed application",
|
||||
"slug": _text(item.get("slug")),
|
||||
"launch_url": _text(item.get("launch_url") or item.get("meta_launch_url")),
|
||||
}
|
||||
|
||||
def groups(self, limit: int = _MAX_COLLECTION_ITEMS) -> dict[str, Any]:
|
||||
"""Return normalized groups; only display-safe identifiers and names are retained."""
|
||||
raw = self._collection("/core/groups/", limit)
|
||||
items = [normalized for item in raw["items"] if (normalized := self._normalize_group(item)) is not None]
|
||||
return {"items": items, "total": raw["total"]}
|
||||
|
||||
def applications(self, limit: int = _MAX_COLLECTION_ITEMS) -> dict[str, Any]:
|
||||
"""Return normalized applications without provider, policy, or secret fields."""
|
||||
raw = self._collection("/core/applications/", limit)
|
||||
return {"items": [self._normalize_application(item) for item in raw["items"]], "total": raw["total"]}
|
||||
|
||||
@staticmethod
|
||||
def _group_references(user: dict[str, Any]) -> list[str]:
|
||||
"""Extract group ids from release-dependent user reference shapes."""
|
||||
raw = user.get("groups", user.get("group", []))
|
||||
if not isinstance(raw, list):
|
||||
raw = [raw] if raw is not None else []
|
||||
ids: list[str] = []
|
||||
for reference in raw:
|
||||
if isinstance(reference, dict):
|
||||
group_id = _identifier(reference)
|
||||
else:
|
||||
group_id = _text(reference)
|
||||
if group_id and group_id not in ids:
|
||||
ids.append(group_id)
|
||||
return ids
|
||||
|
||||
def access_summaries(
|
||||
self,
|
||||
search: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""Return a normalized page of Authentik users.
|
||||
"""Summarize user group references and privileged flags without N+1 user reads.
|
||||
|
||||
Calls ``GET /api/v3/core/users/`` and normalizes the paginated
|
||||
Authentik response into ``{items, total, page, page_size}``. Each item
|
||||
is the raw Authentik user dict (pk, username, name, email, avatar, …)
|
||||
so the frontend can pick the fields it needs.
|
||||
This is directory metadata only: group membership plus the explicit
|
||||
``is_superuser`` and ``is_staff`` fields. It does not evaluate policies
|
||||
or claim to calculate effective authorization.
|
||||
"""
|
||||
payload = self.get(
|
||||
"/core/users/",
|
||||
search=search,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
if not isinstance(payload, dict):
|
||||
logger.warning("Authentik users payload was not a dict: %s", type(payload).__name__)
|
||||
return {"items": [], "total": 0, "page": page, "page_size": page_size}
|
||||
|
||||
results = payload.get("results")
|
||||
items: list[dict[str, Any]] = (
|
||||
[item for item in results if isinstance(item, dict)] if isinstance(results, list) else []
|
||||
)
|
||||
|
||||
pagination = payload.get("pagination") or {}
|
||||
total = 0
|
||||
if isinstance(pagination, dict):
|
||||
try:
|
||||
total = int(pagination.get("count") or 0)
|
||||
except (TypeError, ValueError):
|
||||
total = 0
|
||||
|
||||
logger.info(
|
||||
"Authentik users page=%s page_size=%s -> %s items (total=%s)",
|
||||
page,
|
||||
page_size,
|
||||
len(items),
|
||||
total,
|
||||
)
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
users = self.users(search=search, page=page, page_size=page_size)
|
||||
groups = self.groups()
|
||||
group_names = {group["id"]: group["name"] for group in groups["items"]}
|
||||
summaries: list[dict[str, Any]] = []
|
||||
for user in users["items"]:
|
||||
group_ids = self._group_references(user)
|
||||
summaries.append(
|
||||
{
|
||||
"id": _identifier(user),
|
||||
"username": _text(user.get("username")),
|
||||
"name": _text(user.get("name")),
|
||||
"email": _text(user.get("email")),
|
||||
"is_active": bool(user.get("is_active", True)),
|
||||
"is_superuser": bool(user.get("is_superuser", False)),
|
||||
"is_staff": bool(user.get("is_staff", False)),
|
||||
"groups": [
|
||||
{
|
||||
"id": group_id,
|
||||
"name": group_names.get(group_id, f"Unknown group ({group_id})"),
|
||||
"known": group_id in group_names,
|
||||
}
|
||||
for group_id in group_ids
|
||||
],
|
||||
}
|
||||
)
|
||||
return {"items": summaries, "total": users["total"], "page": users["page"], "page_size": users["page_size"]}
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
"""Authentik service definition.
|
||||
|
||||
Authentik is the user-directory source (replacing the Jellyfin-backed Users
|
||||
page). Its directory API is queried via :class:`AuthentikClient` and surfaced
|
||||
on the Authentik service page (Users + Messaging tabs). OIDC authentication
|
||||
is unchanged -- this service type is for the directory, not SSO.
|
||||
"""
|
||||
"""Authentik service definition for read-only directory and access metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from media_library_viewer_api.clients.authentik import AuthentikClient
|
||||
from media_library_viewer_api.integrations.base import (
|
||||
SecretField,
|
||||
@@ -17,27 +13,25 @@ from media_library_viewer_api.integrations.base import (
|
||||
ServiceConfigBase,
|
||||
ServiceDefinition,
|
||||
TestResult,
|
||||
WidgetConfigBase,
|
||||
translate_connection_error,
|
||||
widget_kind,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from media_library_viewer_api.services.settings_store import SettingsStore
|
||||
|
||||
|
||||
def test_connection(
|
||||
config: dict[str, Any],
|
||||
secrets: dict[str, str],
|
||||
store: SettingsStore,
|
||||
) -> TestResult:
|
||||
"""Probe AuthentikClient.users(page=1, page_size=1) — lightest directory call."""
|
||||
def test_connection(config: dict[str, Any], secrets: dict[str, str], store: SettingsStore) -> TestResult:
|
||||
"""Probe the least-expensive Authentik directory endpoint."""
|
||||
try:
|
||||
base_url = str(config.get("base_url") or "").rstrip("/")
|
||||
api_token = str(secrets.get("api_token") or "")
|
||||
timeout = float(config.get("timeout_seconds") or 60)
|
||||
client = AuthentikClient(base_url=base_url, api_token=api_token, timeout=timeout)
|
||||
client = AuthentikClient(
|
||||
base_url=str(config.get("base_url") or "").rstrip("/"),
|
||||
api_token=str(secrets.get("api_token") or ""),
|
||||
timeout=float(config.get("timeout_seconds") or 60),
|
||||
)
|
||||
result = client.users(page=1, page_size=1)
|
||||
total = result.get("total", 0) if isinstance(result, dict) else 0
|
||||
return TestResult(ok=True, detail="Connected to Authentik.", evidence=f"{total} users")
|
||||
return TestResult(ok=True, detail="Connected to Authentik.", evidence=f"{result.get('total', 0)} users")
|
||||
except Exception as exc:
|
||||
return translate_connection_error(exc, context="Authentik")
|
||||
|
||||
@@ -46,17 +40,46 @@ class AuthentikConfig(ServiceConfigBase):
|
||||
"""Non-secret Authentik connection config."""
|
||||
|
||||
base_url: ServiceBaseUrl
|
||||
timeout_seconds: int = 60
|
||||
timeout_seconds: int = Field(default=60, ge=1, le=300)
|
||||
|
||||
|
||||
class AuthentikListWidgetConfig(WidgetConfigBase):
|
||||
"""Bounded display count for read-only Authentik list widgets."""
|
||||
|
||||
limit: int = Field(default=10, ge=1, le=50)
|
||||
|
||||
|
||||
DEFINITION = ServiceDefinition(
|
||||
service_type="authentik",
|
||||
name="Authentik",
|
||||
description="User directory and identity provider integration.",
|
||||
description="Read-only user directory, groups, and application access metadata.",
|
||||
config_model=AuthentikConfig,
|
||||
secret_fields=[
|
||||
SecretField(key="api_token", label="API token", required=True),
|
||||
secret_fields=[SecretField(key="api_token", label="API token", required=True)],
|
||||
widget_kinds=[
|
||||
widget_kind(
|
||||
kind="access_summary",
|
||||
name="User access summary",
|
||||
description="User group memberships and explicit staff/superuser status; not effective authorization.",
|
||||
model_cls=AuthentikListWidgetConfig,
|
||||
default_config={"limit": 10},
|
||||
refresh_interval_ms=60_000,
|
||||
),
|
||||
widget_kind(
|
||||
kind="groups",
|
||||
name="Groups",
|
||||
description="Read-only Authentik group list.",
|
||||
model_cls=AuthentikListWidgetConfig,
|
||||
default_config={"limit": 10},
|
||||
refresh_interval_ms=60_000,
|
||||
),
|
||||
widget_kind(
|
||||
kind="applications",
|
||||
name="Applications",
|
||||
description="Read-only Authentik application list.",
|
||||
model_cls=AuthentikListWidgetConfig,
|
||||
default_config={"limit": 10},
|
||||
refresh_interval_ms=60_000,
|
||||
),
|
||||
],
|
||||
widget_kinds=[],
|
||||
test_callable=test_connection,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""Authentik directory + messaging router.
|
||||
"""Read-only Authentik directory, access metadata, and messaging router.
|
||||
|
||||
Resolves an ``authentik`` service instance from the registry, builds an
|
||||
:class:`AuthentikClient` from its config + decrypted ``api_token`` secret, and
|
||||
proxies paginated directory queries plus message-compose (email enqueue).
|
||||
Graceful "not configured" / "unreachable" payloads (matching the monitoring
|
||||
router's pattern) so the UI always renders.
|
||||
Directory data is service-scoped and fails gracefully so the service page can
|
||||
render a useful empty/error state when Authentik is unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +9,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
|
||||
from media_library_viewer_api.clients.authentik import AuthentikClient
|
||||
@@ -30,7 +27,7 @@ router = APIRouter(prefix="/api/services/authentik", tags=["authentik"])
|
||||
|
||||
|
||||
class MessageRequest(BaseModel):
|
||||
"""Compose-request body for the Authentik messaging endpoint."""
|
||||
"""Compose-request body for the existing Authentik messaging endpoint."""
|
||||
|
||||
recipient_emails: list[str]
|
||||
subject: str
|
||||
@@ -38,39 +35,99 @@ class MessageRequest(BaseModel):
|
||||
|
||||
|
||||
def _build_client(service: ServiceRecord) -> AuthentikClient:
|
||||
base_url = str(service.config.get("base_url") or "").rstrip("/")
|
||||
api_token = str(service.secrets.get("api_token") or "")
|
||||
try:
|
||||
timeout = float(service.config.get("timeout_seconds") or 10)
|
||||
except (TypeError, ValueError):
|
||||
timeout = 10.0
|
||||
return AuthentikClient(base_url=base_url, api_token=api_token, timeout=timeout)
|
||||
return AuthentikClient(
|
||||
base_url=str(service.config.get("base_url") or "").rstrip("/"),
|
||||
api_token=str(service.secrets.get("api_token") or ""),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _empty(error: str) -> dict[str, Any]:
|
||||
def _empty_directory(error: str) -> dict[str, Any]:
|
||||
return {"items": [], "total": 0, "page": 1, "page_size": 50, "error": error}
|
||||
|
||||
|
||||
def _empty_collection(error: str) -> dict[str, Any]:
|
||||
return {"items": [], "total": 0, "error": error}
|
||||
|
||||
|
||||
def _service_or_error(store: SettingsStore, service_id: str) -> ServiceRecord | None:
|
||||
return resolve_service_record(store, "authentik", service_id)
|
||||
|
||||
|
||||
@router.get("/{service_id}/users")
|
||||
def get_authentik_users(
|
||||
service_id: str,
|
||||
search: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=50, ge=1, le=200),
|
||||
store: SettingsStore = Depends(get_settings_store),
|
||||
) -> dict[str, Any]:
|
||||
"""Paginated Authentik user directory for a specific service instance."""
|
||||
service = resolve_service_record(store, "authentik", service_id)
|
||||
"""Paginated raw directory users for the existing messaging surface."""
|
||||
service = _service_or_error(store, service_id)
|
||||
if service is None:
|
||||
logger.info("Authentik users requested but no enabled authentik service for id=%s", service_id)
|
||||
return _empty("Authentik service not configured")
|
||||
|
||||
return _empty_directory("Authentik service not configured")
|
||||
try:
|
||||
client = _build_client(service)
|
||||
return client.users(search=search, page=page, page_size=page_size)
|
||||
return _build_client(service).users(search=search, page=page, page_size=page_size)
|
||||
except Exception:
|
||||
logger.exception("Authentik users query failed for service %s", service_id)
|
||||
return _empty("Authentik is unreachable")
|
||||
return _empty_directory("Authentik is unreachable")
|
||||
|
||||
|
||||
@router.get("/{service_id}/access-summary")
|
||||
def get_authentik_access_summary(
|
||||
service_id: str,
|
||||
search: str | None = None,
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=50, ge=1, le=200),
|
||||
store: SettingsStore = Depends(get_settings_store),
|
||||
) -> dict[str, Any]:
|
||||
"""User groups plus explicit staff/superuser flags, not effective permissions."""
|
||||
service = _service_or_error(store, service_id)
|
||||
if service is None:
|
||||
return _empty_directory("Authentik service not configured")
|
||||
try:
|
||||
return _build_client(service).access_summaries(search=search, page=page, page_size=page_size)
|
||||
except Exception:
|
||||
logger.exception("Authentik access summary query failed for service %s", service_id)
|
||||
return _empty_directory("Authentik is unreachable")
|
||||
|
||||
|
||||
@router.get("/{service_id}/groups")
|
||||
def get_authentik_groups(
|
||||
service_id: str,
|
||||
limit: int = Query(default=100, ge=1, le=200),
|
||||
store: SettingsStore = Depends(get_settings_store),
|
||||
) -> dict[str, Any]:
|
||||
"""Display-safe, service-scoped Authentik group list."""
|
||||
service = _service_or_error(store, service_id)
|
||||
if service is None:
|
||||
return _empty_collection("Authentik service not configured")
|
||||
try:
|
||||
return _build_client(service).groups(limit=limit)
|
||||
except Exception:
|
||||
logger.exception("Authentik groups query failed for service %s", service_id)
|
||||
return _empty_collection("Authentik is unreachable")
|
||||
|
||||
|
||||
@router.get("/{service_id}/applications")
|
||||
def get_authentik_applications(
|
||||
service_id: str,
|
||||
limit: int = Query(default=100, ge=1, le=200),
|
||||
store: SettingsStore = Depends(get_settings_store),
|
||||
) -> dict[str, Any]:
|
||||
"""Display-safe Authentik applications without provider or policy details."""
|
||||
service = _service_or_error(store, service_id)
|
||||
if service is None:
|
||||
return _empty_collection("Authentik service not configured")
|
||||
try:
|
||||
return _build_client(service).applications(limit=limit)
|
||||
except Exception:
|
||||
logger.exception("Authentik applications query failed for service %s", service_id)
|
||||
return _empty_collection("Authentik is unreachable")
|
||||
|
||||
|
||||
@router.get("/{service_id}/message/status")
|
||||
@@ -80,8 +137,7 @@ def get_authentik_message_status(
|
||||
mail_queue: MailQueue = Depends(get_mail_queue),
|
||||
) -> dict[str, Any]:
|
||||
"""Mail-queue status snapshot for the Authentik messaging tab."""
|
||||
service = resolve_service_record(store, "authentik", service_id)
|
||||
if service is None:
|
||||
if _service_or_error(store, service_id) is None:
|
||||
return {"state": "stopped", "worker_running": False, "error": "Authentik service not configured"}
|
||||
return mail_queue.status()
|
||||
|
||||
@@ -94,20 +150,16 @@ def post_authentik_message(
|
||||
mail_queue: MailQueue = Depends(get_mail_queue),
|
||||
) -> dict[str, Any]:
|
||||
"""Enqueue an email to Authentik-sourced recipients via the mail queue."""
|
||||
service = resolve_service_record(store, "authentik", service_id)
|
||||
if service is None:
|
||||
if _service_or_error(store, service_id) is None:
|
||||
return {"status": "error", "error": "Authentik service not configured"}
|
||||
|
||||
recipients = [r.strip() for r in body.recipient_emails if r.strip()]
|
||||
recipients = [recipient.strip() for recipient in body.recipient_emails if recipient.strip()]
|
||||
if not recipients:
|
||||
return {"status": "error", "error": "No recipients with valid email addresses."}
|
||||
|
||||
settings = get_settings()
|
||||
try:
|
||||
validate_smtp_settings(settings)
|
||||
except ValueError as exc:
|
||||
return {"status": "error", "error": f"SMTP settings invalid: {exc}"}
|
||||
|
||||
request_id = mail_queue.enqueue(
|
||||
settings=settings,
|
||||
recipients=recipients,
|
||||
@@ -115,8 +167,4 @@ def post_authentik_message(
|
||||
html_body=body.html_body,
|
||||
)
|
||||
logger.info("Authentik message enqueued for service %s (%d recipients)", service_id, len(recipients))
|
||||
return {
|
||||
"status": "queued",
|
||||
"request_id": request_id,
|
||||
"recipient_count": len(recipients),
|
||||
}
|
||||
return {"status": "queued", "request_id": request_id, "recipient_count": len(recipients)}
|
||||
|
||||
@@ -19,6 +19,7 @@ from typing import Any, Protocol
|
||||
|
||||
import requests
|
||||
|
||||
from media_library_viewer_api.clients.authentik import AuthentikClient
|
||||
from media_library_viewer_api.clients.jellyfin import JellyfinClient
|
||||
from media_library_viewer_api.clients.qbittorrent import QbittorrentClient
|
||||
from media_library_viewer_api.domain.dashboard import (
|
||||
@@ -316,6 +317,36 @@ class AlertmanagerWidgetSource:
|
||||
return {"error": f"Alertmanager query failed: {exc}"}
|
||||
|
||||
|
||||
class AuthentikWidgetSource:
|
||||
"""Fetch bounded, display-safe Authentik directory metadata."""
|
||||
|
||||
async def fetch(self, service: ServiceRecord | None, widget_kind: str, config: dict[str, Any]) -> dict[str, Any]:
|
||||
try:
|
||||
if service is None:
|
||||
return {"error": "Authentik widget is missing its service"}
|
||||
base_url = str(service.config.get("base_url") or "")
|
||||
api_token = str(service.secrets.get("api_token") or "")
|
||||
timeout = _safe_int(service.config.get("timeout_seconds") or 60, 60)
|
||||
limit = max(1, min(_safe_int(config.get("limit") or 10, 10), 50))
|
||||
client = await asyncio.wait_for(
|
||||
asyncio.to_thread(AuthentikClient, base_url, api_token, timeout), timeout=timeout
|
||||
)
|
||||
if widget_kind == "access_summary":
|
||||
return await asyncio.wait_for(
|
||||
asyncio.to_thread(client.access_summaries, page=1, page_size=limit), timeout=timeout
|
||||
)
|
||||
if widget_kind == "groups":
|
||||
return await asyncio.wait_for(asyncio.to_thread(client.groups, limit=limit), timeout=timeout)
|
||||
if widget_kind == "applications":
|
||||
return await asyncio.wait_for(asyncio.to_thread(client.applications, limit=limit), timeout=timeout)
|
||||
return {"error": f"Unknown Authentik widget kind: {widget_kind}"}
|
||||
except asyncio.TimeoutError as _timeout_error:
|
||||
return {"error": "Authentik data fetch timed out"}
|
||||
except Exception as exc:
|
||||
logger.exception("authentik adapter failed")
|
||||
return {"error": f"Authentik data fetch failed: {exc}"}
|
||||
|
||||
|
||||
class JellyfinWidgetSource:
|
||||
"""Fetch Jellyfin sessions and map them to activity rows."""
|
||||
|
||||
@@ -531,6 +562,7 @@ SERVICE_ADAPTERS: dict[str, WidgetSource] = {
|
||||
"qbittorrent": QbittorrentWidgetSource(),
|
||||
"alertmanager": AlertmanagerWidgetSource(),
|
||||
"jellyfin": JellyfinWidgetSource(),
|
||||
"authentik": AuthentikWidgetSource(),
|
||||
"remote_machine": SshTaskWidgetSource(),
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user