- GET /auth/groups - list groups with search/pagination - POST /auth/groups/sync-from-authentik - bulk sync from Authentik - Group model and database migration 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.5
parent
3516376d92
commit
e85c9a123d
+156
-2
@@ -15,8 +15,8 @@ from sqlalchemy.orm import selectinload
|
||||
|
||||
from src.config import get_settings
|
||||
from src.logging_config import get_logger
|
||||
from src.db.models import User, Role, UserPreferences
|
||||
from src.auth.schemas import TokenInfoSchema, UserSchema, RoleSchema, UserPreferencesSchema, UserListItemSchema, BulkSyncResultSchema
|
||||
from src.db.models import User, Role, UserPreferences, Group
|
||||
from src.auth.schemas import TokenInfoSchema, UserSchema, RoleSchema, UserPreferencesSchema, UserListItemSchema, BulkSyncResultSchema, GroupListItemSchema
|
||||
|
||||
logger = get_logger(__name__)
|
||||
settings = get_settings()
|
||||
@@ -470,6 +470,160 @@ class AuthService:
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def list_groups(
|
||||
self,
|
||||
search: Optional[str] = None,
|
||||
offset: int = 0,
|
||||
limit: int = 50,
|
||||
) -> tuple[list[GroupListItemSchema], int]:
|
||||
"""
|
||||
List all groups with optional search and pagination
|
||||
|
||||
Args:
|
||||
search: Optional search query (matches name)
|
||||
offset: Number of records to skip
|
||||
limit: Maximum number of records to return
|
||||
|
||||
Returns:
|
||||
Tuple of (list of group schemas, total count)
|
||||
"""
|
||||
from sqlalchemy import func
|
||||
|
||||
# Base query
|
||||
base_query = select(Group)
|
||||
|
||||
# Apply search filter if provided
|
||||
if search:
|
||||
search_filter = f"%{search}%"
|
||||
base_query = base_query.where(Group.name.ilike(search_filter))
|
||||
|
||||
# Get total count
|
||||
count_query = select(func.count()).select_from(base_query.subquery())
|
||||
total_result = await self.session.execute(count_query)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
# Apply pagination and ordering
|
||||
query = base_query.order_by(Group.name).offset(offset).limit(limit)
|
||||
result = await self.session.execute(query)
|
||||
groups = list(result.scalars().all())
|
||||
|
||||
# Convert to schemas
|
||||
items = [
|
||||
GroupListItemSchema(
|
||||
id=group.id,
|
||||
authentik_id=group.authentik_id,
|
||||
name=group.name,
|
||||
is_superuser=group.is_superuser,
|
||||
parent_name=group.parent_name,
|
||||
member_count=group.member_count,
|
||||
synced_at=group.synced_at,
|
||||
)
|
||||
for group in groups
|
||||
]
|
||||
|
||||
return items, total
|
||||
|
||||
async def bulk_sync_groups_from_authentik(self) -> BulkSyncResultSchema:
|
||||
"""
|
||||
Fetch all groups from Authentik admin API and sync to local database
|
||||
|
||||
Returns:
|
||||
BulkSyncResultSchema with counts of created/updated/failed groups
|
||||
"""
|
||||
if not settings.authentik_username or not settings.authentik_password:
|
||||
raise ValueError("AUTHENTIK_USERNAME and AUTHENTIK_PASSWORD must be configured")
|
||||
|
||||
created = 0
|
||||
updated = 0
|
||||
failed = 0
|
||||
errors = []
|
||||
total_in_authentik = 0
|
||||
|
||||
# Step 1: Fetch all group data from Authentik API
|
||||
authentik_groups = []
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:
|
||||
# Authenticate with Authentik to get session cookie
|
||||
session_cookie = await self._authentik_session_login(client)
|
||||
|
||||
# Fetch groups from Authentik admin API using session cookie
|
||||
response = await client.get(
|
||||
f"{settings.authentik_url}/api/v3/core/groups/",
|
||||
params={"page_size": 500},
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Cookie": f"authentik_session={session_cookie}",
|
||||
},
|
||||
)
|
||||
|
||||
if response.status_code == 401:
|
||||
raise ValueError("Authentik API token is invalid or expired")
|
||||
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
authentik_groups = data.get("results", [])
|
||||
total_in_authentik = data.get("pagination", {}).get("count", len(authentik_groups))
|
||||
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise ValueError(f"Authentik API error: {e.response.status_code}")
|
||||
except httpx.RequestError as e:
|
||||
raise ValueError(f"Failed to connect to Authentik: {str(e)}")
|
||||
|
||||
# Step 2: Sync groups to database (outside of httpx context to avoid greenlet issues)
|
||||
for auth_group in authentik_groups:
|
||||
try:
|
||||
# Extract group data from Authentik
|
||||
authentik_id = uuid.UUID(auth_group["pk"])
|
||||
name = auth_group.get("name", "Unknown")
|
||||
is_superuser = auth_group.get("is_superuser", False)
|
||||
parent_name = auth_group.get("parent_name")
|
||||
# users field contains list of user PKs
|
||||
member_count = len(auth_group.get("users", []))
|
||||
|
||||
# Check if group exists
|
||||
stmt = select(Group).where(Group.authentik_id == authentik_id)
|
||||
result = await self.session.execute(stmt)
|
||||
group = result.scalar_one_or_none()
|
||||
|
||||
if group is None:
|
||||
# Create new group
|
||||
group = Group(
|
||||
authentik_id=authentik_id,
|
||||
name=name,
|
||||
is_superuser=is_superuser,
|
||||
parent_name=parent_name,
|
||||
member_count=member_count,
|
||||
)
|
||||
self.session.add(group)
|
||||
created += 1
|
||||
logger.info(f"Created group from Authentik: {name}")
|
||||
else:
|
||||
# Update existing group
|
||||
group.name = name
|
||||
group.is_superuser = is_superuser
|
||||
group.parent_name = parent_name
|
||||
group.member_count = member_count
|
||||
updated += 1
|
||||
logger.info(f"Updated group from Authentik: {name}")
|
||||
|
||||
except Exception as e:
|
||||
failed += 1
|
||||
error_msg = f"Failed to sync group {auth_group.get('name', 'unknown')}: {str(e)}"
|
||||
errors.append(error_msg)
|
||||
logger.warning(error_msg)
|
||||
|
||||
# Commit all changes
|
||||
await self.session.commit()
|
||||
|
||||
return BulkSyncResultSchema(
|
||||
created=created,
|
||||
updated=updated,
|
||||
failed=failed,
|
||||
total_in_authentik=total_in_authentik,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
# Factory function for dependency injection
|
||||
def get_auth_service(session: AsyncSession) -> AuthService:
|
||||
|
||||
Reference in New Issue
Block a user