- Add V1 API routes for assets, ledger, and user info with complete CRUD operations - Implement authentication scopes and request validation via auth_routes.py - Extend schemas with V1-specific models for accounts, holdings, and positions - Add database queries and aggregations for P&L, performance, and account data - Include comprehensive test coverage for all V1 endpoints and integration flows - Update batch and release documentation with implementation and verification evidence - Sync project structure and runtime flows per V1 API contract requirements Closes implementation phase of BAT-001 (TrEx Basic V1 API Contract)
87 lines
3.1 KiB
Python
87 lines
3.1 KiB
Python
"""GET /v1/user_info — service-token authenticated user info endpoint."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
|
|
from app.core.auth import AuthContext, require_read
|
|
from app.core.config import Settings, get_settings
|
|
from app.core.encryption import InvalidToken, decrypt_payload
|
|
from app.repositories.factory import get_portfolio_repository_from_settings
|
|
from app.schemas.v1 import BrokerItem, UserInfoResponse
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/v1", tags=["v1"])
|
|
|
|
|
|
def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthContext:
|
|
if auth.token_source != "db" or auth.token_type != "service":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Service token required",
|
|
)
|
|
return auth
|
|
|
|
|
|
@router.get("/user_info", response_model=UserInfoResponse)
|
|
def get_user_info(
|
|
auth: AuthContext = Depends(_require_service_token),
|
|
settings: Settings = Depends(get_settings),
|
|
) -> UserInfoResponse:
|
|
if not auth.runtime_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail="runtime_id not assigned to this token",
|
|
)
|
|
|
|
repo = get_portfolio_repository_from_settings(settings)
|
|
try:
|
|
user = repo.get_user(auth.user_id) # type: ignore[arg-type]
|
|
|
|
# Fetch broker credentials and decrypt
|
|
brokers: list[BrokerItem] = []
|
|
try:
|
|
credentials = repo.list_broker_credentials(auth.user_id) # type: ignore[arg-type]
|
|
enc_key: str | None = None
|
|
for cred in credentials:
|
|
credential_payload = None
|
|
try:
|
|
if enc_key is None:
|
|
enc_key = settings.require_credential_encryption_key()
|
|
raw = decrypt_payload(enc_key, cred.encrypted_payload)
|
|
credential_payload = json.loads(raw)
|
|
except (InvalidToken, RuntimeError, Exception) as exc:
|
|
logger.warning("credential decryption failed for broker %s: %s", cred.broker, exc)
|
|
brokers.append(BrokerItem(
|
|
broker=cred.broker,
|
|
account_ref=cred.account_ref,
|
|
credential_payload=credential_payload,
|
|
credential_version=cred.credential_version,
|
|
last_rotated_at=cred.last_rotated_at,
|
|
))
|
|
except AttributeError:
|
|
# repo does not implement list_broker_credentials yet (mock or older impl)
|
|
pass
|
|
|
|
finally:
|
|
if callable(getattr(type(repo), "close", None)):
|
|
repo.close()
|
|
|
|
disabled_reason: str | None = None
|
|
if not user.is_active:
|
|
disabled_reason = "account_inactive"
|
|
|
|
return UserInfoResponse(
|
|
runtime_id=auth.runtime_id,
|
|
trading_enabled=user.is_active,
|
|
disabled_reason=disabled_reason,
|
|
brokers=brokers,
|
|
user_id=user.id,
|
|
username=user.username,
|
|
email=user.email,
|
|
permission=user.permission,
|
|
)
|