feat: add Nailong Fund advisor capabilities
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi import Depends, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
|
||||
from app.core.config import get_settings
|
||||
from app.core.contracts import RequestContext
|
||||
from app.core.errors import UnauthorizedAgentError
|
||||
from app.core.security import JwtAuthenticator
|
||||
from app.service.identity_service import IdentityService
|
||||
from app.service.risk_questionnaire_service import RiskQuestionnaireService
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
TRACE_ID_HEADER = "X-Trace-ID"
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
@@ -20,16 +23,18 @@ async def build_request_context(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer), # noqa: B008
|
||||
) -> RequestContext:
|
||||
request.state.trace_id = request.headers.get(TRACE_ID_HEADER)
|
||||
if credentials is None or credentials.scheme.lower() != "bearer":
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")
|
||||
raise UnauthorizedAgentError("token is missing, invalid, or revoked")
|
||||
try:
|
||||
context = _authenticator().authenticate(credentials.credentials)
|
||||
context = await IdentityService().resolve(context)
|
||||
except Exception as exc:
|
||||
from app.core.errors import UnauthorizedAgentError
|
||||
|
||||
if isinstance(exc, UnauthorizedAgentError):
|
||||
raise HTTPException(status_code=401, detail="Unauthorized") from exc
|
||||
raise
|
||||
raise UnauthorizedAgentError("token is missing, invalid, or revoked") from exc
|
||||
request.state.request_context = context
|
||||
onboarding_path = request.url.path.startswith("/api/v1/onboarding/")
|
||||
if not onboarding_path and await RiskQuestionnaireService().is_required(context):
|
||||
from app.core.errors import OnboardingRequiredError
|
||||
|
||||
raise OnboardingRequiredError("请先完成开户风险测评问卷")
|
||||
return context
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Authenticated per-route request rate limiting."""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import Depends, Request
|
||||
|
||||
from app.api.dependencies.auth import build_request_context
|
||||
from app.core.config import get_settings
|
||||
from app.core.contracts import RequestContext
|
||||
from app.core.rate_limit import RateLimitExceededError, RateLimitPolicy
|
||||
from app.infrastructure.rate_limiter import CounterBackend, default_counter_backend
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_counter_backend() -> CounterBackend:
|
||||
return default_counter_backend()
|
||||
|
||||
|
||||
def route_template(request: Request) -> str:
|
||||
route = request.scope.get("route")
|
||||
return str(getattr(route, "path", request.url.path))
|
||||
|
||||
|
||||
async def enforce_rate_limit(
|
||||
request: Request,
|
||||
context: RequestContext = Depends(build_request_context), # noqa: B008
|
||||
) -> None:
|
||||
policy = RateLimitPolicy.from_settings(get_settings())
|
||||
if not policy.enabled:
|
||||
return
|
||||
result = await get_counter_backend().increment(
|
||||
policy.key(context.user_id, request.method, route_template(request)),
|
||||
policy.window_seconds,
|
||||
)
|
||||
if result is None:
|
||||
logger.warning("rate limit backend unavailable; allowing route=%s", request.url.path)
|
||||
return
|
||||
count, retry_after_seconds = result
|
||||
if count > policy.max_requests:
|
||||
raise RateLimitExceededError("request rate limit exceeded", retry_after_seconds)
|
||||
Reference in New Issue
Block a user