2026-03-13 16:41:34 +01:00
|
|
|
import hmac
|
|
|
|
|
|
|
|
|
|
from fastapi import Depends, Header, HTTPException, Request, status
|
2026-03-06 23:14:34 +01:00
|
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
|
|
|
|
2026-03-13 16:41:34 +01:00
|
|
|
from app.core.config import settings
|
2026-03-06 23:14:34 +01:00
|
|
|
from app.core.security import decode_token
|
|
|
|
|
|
2026-03-13 16:41:34 +01:00
|
|
|
bearer = HTTPBearer(auto_error=False)
|
|
|
|
|
|
2026-03-06 23:14:34 +01:00
|
|
|
|
2026-03-13 16:41:34 +01:00
|
|
|
def get_current_user(
|
|
|
|
|
request: Request,
|
|
|
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
|
|
|
|
|
x_mcp_service_key: str | None = Header(default=None),
|
|
|
|
|
) -> str:
|
|
|
|
|
# 1. MCP service key (Docker-internal only — backend port is not externally exposed)
|
|
|
|
|
if x_mcp_service_key is not None:
|
|
|
|
|
if not settings.mcp_service_key:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="MCP service key not configured")
|
|
|
|
|
if not hmac.compare_digest(x_mcp_service_key.encode(), settings.mcp_service_key.encode()):
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid MCP service key")
|
|
|
|
|
return "__mcp_service__"
|
2026-03-06 23:14:34 +01:00
|
|
|
|
2026-03-13 16:41:34 +01:00
|
|
|
# 2. Standard JWT bearer token
|
|
|
|
|
if credentials is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
2026-03-06 23:14:34 +01:00
|
|
|
username = decode_token(credentials.credentials)
|
|
|
|
|
if not username:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
|
|
|
return username
|