ForcePilot/backend/package/yuxi/channel/application/service/auth_service.py
Kris 9a8a27bf36 feat(channel): 新增渠道网关模块完整实现
本次提交新增了完整的多渠道消息网关系统,包括:
1. 支持飞书、钉钉、Web、Hook 四种渠道的适配器与配置
2. 领域模型层:消息、会话、绑定、出箱等核心实体
3. 应用服务层:管道、中间件、DTO 与业务逻辑
4. 基础设施层:持久化、过滤器、队列等端口实现
5. 接口层:REST API、SSE、WebSocket 通信端点
6. 前端页面与路由配置,添加渠道管理菜单
7. 新增相关依赖包与 docker-compose 部署配置
2026-05-30 21:53:09 +08:00

71 lines
2.3 KiB
Python

from __future__ import annotations
import base64
import hmac
from yuxi.channel.domain.port.rate_limit_port import RateLimitPort
class AuthService:
def __init__(
self,
rate_limit_port: RateLimitPort,
*,
token: str | None = None,
password: str | None = None,
max_attempts: int = 5,
lockout_seconds: int = 300,
) -> None:
self._rate_limiter = rate_limit_port
self._token = token
self._password = password
self._max_attempts = max_attempts
self._lockout_seconds = lockout_seconds
def update_credentials(self, *, token: str | None = None, password: str | None = None) -> None:
if token is not None:
self._token = token
if password is not None:
self._password = password
async def authenticate(self, auth_header: str, *, client_id: str = "unknown") -> tuple[bool, str]:
if not self._token and not self._password:
return True, ""
locked, remaining = await self._rate_limiter.is_locked(f"channel:auth:lockout:{client_id}")
if locked:
return False, f"auth rate limited, retry after {remaining}s"
if self._check_credential(auth_header):
await self._rate_limiter.reset(f"channel:auth:attempts:{client_id}")
return True, ""
allowed = await self._rate_limiter.check_and_incr(
f"channel:auth:attempts:{client_id}",
max_attempts=self._max_attempts,
window_seconds=self._lockout_seconds,
lockout_seconds=self._lockout_seconds,
)
if not allowed:
return False, "auth rate limited"
return False, "auth failed"
def _check_credential(self, auth_header: str) -> bool:
if auth_header.startswith("Bearer "):
if self._token:
return _safe_compare(auth_header[7:], self._token)
if auth_header.startswith("Basic "):
try:
decoded = base64.b64decode(auth_header[6:]).decode()
if ":" in decoded and self._password:
_, pwd = decoded.split(":", 1)
return _safe_compare(pwd, self._password)
except Exception:
pass
return False
def _safe_compare(a: str, b: str) -> bool:
return hmac.compare_digest(a.encode(), b.encode())