191 lines
7.0 KiB
Python
191 lines
7.0 KiB
Python
"""Client for interacting with the common platform API."""
|
|
|
|
import httpx
|
|
from typing import Optional, List, Dict, Any
|
|
from app.settings import get_settings
|
|
from app.core.logging import logger
|
|
|
|
|
|
class PlatformUser:
|
|
"""Wrapper for user data from the platform."""
|
|
|
|
def __init__(
|
|
self,
|
|
id: int,
|
|
email: str,
|
|
first_name: str = "",
|
|
last_name: str = "",
|
|
is_active: bool = True,
|
|
roles: Optional[List[str]] = None,
|
|
):
|
|
self.id = id
|
|
self.email = email
|
|
self.first_name = first_name
|
|
self.last_name = last_name
|
|
self.is_active = is_active
|
|
self.roles = roles or []
|
|
|
|
@property
|
|
def display_name(self) -> str:
|
|
if self.first_name or self.last_name:
|
|
return f"{self.first_name} {self.last_name}".strip()
|
|
return self.email
|
|
|
|
def has_role(self, role_name: str) -> bool:
|
|
return role_name in self.roles
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"id": self.id,
|
|
"email": self.email,
|
|
"first_name": self.first_name,
|
|
"last_name": self.last_name,
|
|
"is_active": self.is_active,
|
|
"roles": self.roles,
|
|
}
|
|
|
|
|
|
class PlatformClient:
|
|
"""Client for the common platform REST API."""
|
|
|
|
def __init__(self):
|
|
settings = get_settings()
|
|
self.base_url = settings.PLATFORM_API_URL.rstrip("/")
|
|
self.api_key = settings.PLATFORM_API_KEY
|
|
self.timeout = 10.0
|
|
|
|
def _get_headers(self, token: Optional[str] = None) -> Dict[str, str]:
|
|
headers = {"Content-Type": "application/json"}
|
|
if self.api_key:
|
|
headers["X-API-Key"] = self.api_key
|
|
if token:
|
|
headers["Authorization"] = f"Bearer {token}"
|
|
return headers
|
|
|
|
async def validate_token(self, token: str) -> Optional[PlatformUser]:
|
|
"""Validate JWT token with the platform and return user data."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.post(
|
|
f"{self.base_url}/api/v1/auth/validate",
|
|
headers=self._get_headers(token),
|
|
)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
return PlatformUser(
|
|
id=data["user_id"],
|
|
email=data.get("email", ""),
|
|
first_name=data.get("first_name", ""),
|
|
last_name=data.get("last_name", ""),
|
|
is_active=data.get("is_active", True),
|
|
roles=data.get("roles", []),
|
|
)
|
|
logger.warning(f"Token validation failed: {response.status_code}")
|
|
return None
|
|
except Exception as e:
|
|
logger.error(f"Platform token validation error: {e}")
|
|
return None
|
|
|
|
async def get_user_info(self, user_id: int) -> Optional[PlatformUser]:
|
|
"""Get user information from the platform."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.get(
|
|
f"{self.base_url}/api/v1/users/{user_id}",
|
|
headers=self._get_headers(),
|
|
)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
return PlatformUser(
|
|
id=data["id"],
|
|
email=data.get("email", ""),
|
|
first_name=data.get("first_name", ""),
|
|
last_name=data.get("last_name", ""),
|
|
is_active=data.get("is_active", True),
|
|
roles=data.get("roles", []),
|
|
)
|
|
logger.warning(f"Get user info failed: {response.status_code}")
|
|
return None
|
|
except Exception as e:
|
|
logger.error(f"Platform get user error: {e}")
|
|
return None
|
|
|
|
async def get_user_roles(self, user_id: int) -> List[str]:
|
|
"""Get user roles from the platform."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.get(
|
|
f"{self.base_url}/api/v1/users/{user_id}/roles",
|
|
headers=self._get_headers(),
|
|
)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
return data.get("roles", [])
|
|
return []
|
|
except Exception as e:
|
|
logger.error(f"Platform get user roles error: {e}")
|
|
return []
|
|
|
|
async def get_users(
|
|
self, page: int = 1, page_size: int = 100, search: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""Get paginated list of users from the platform."""
|
|
try:
|
|
params = {"page": page, "page_size": page_size}
|
|
if search:
|
|
params["search"] = search
|
|
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.get(
|
|
f"{self.base_url}/api/v1/users",
|
|
headers=self._get_headers(),
|
|
params=params,
|
|
)
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
users = [
|
|
PlatformUser(
|
|
id=u["id"],
|
|
email=u.get("email", ""),
|
|
first_name=u.get("first_name", ""),
|
|
last_name=u.get("last_name", ""),
|
|
is_active=u.get("is_active", True),
|
|
roles=u.get("roles", []),
|
|
)
|
|
for u in data.get("users", [])
|
|
]
|
|
return {
|
|
"users": users,
|
|
"total": data.get("total", 0),
|
|
}
|
|
return {"users": [], "total": 0}
|
|
except Exception as e:
|
|
logger.error(f"Platform get users error: {e}")
|
|
return {"users": [], "total": 0}
|
|
|
|
async def check_permission(self, user_id: int, permission: str) -> bool:
|
|
"""Check if user has a specific permission on the platform."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
response = await client.get(
|
|
f"{self.base_url}/api/v1/users/{user_id}/permissions/{permission}",
|
|
headers=self._get_headers(),
|
|
)
|
|
return response.status_code == 200 and response.json().get(
|
|
"allowed", False
|
|
)
|
|
except Exception as e:
|
|
logger.error(f"Platform check permission error: {e}")
|
|
return False
|
|
|
|
|
|
_platform_client: Optional[PlatformClient] = None
|
|
|
|
|
|
def get_platform_client() -> PlatformClient:
|
|
"""Get or create the platform client singleton."""
|
|
global _platform_client
|
|
if _platform_client is None:
|
|
_platform_client = PlatformClient()
|
|
return _platform_client
|