ForcePilot/backend/package/yuxi/channel/application/service/auth_service.py
Kris c61d5f0163 feat: 完成通道服务多轮功能迭代
本次提交完成了一系列核心功能迭代与优化:
1.  新增并完善了多个领域模型与端口定义,补充了`__all__`导出规范
2.  优化了会话、绑定、出箱等模块的数据模型,修复了时间字段类型不一致问题
3.  新增了代理ID解析、缓存发布等接口,扩展了系统能力
4.  重构了去重中间件逻辑,优化了空内容校验规则
5.  新增了认证中间件的匿名访问支持,完善了鉴权流程
6.  优化了SSE连接管理,增加了单会话连接上限限制
7.  重构了消息日志与仓储相关代码,将数据类迁移至对应模型目录
8.  新增了重复绑定校验、绑定更新接口,完善了绑定服务逻辑
9.  优化了健康检查逻辑,新增了环境变量控制启动时间线展示
10. 重构了出箱重试工作线程,使用缓存端口替代直接redis操作,新增了消息处理标记逻辑
11. 完善了飞书、Web、钩子等通道的翻译器逻辑,补充了账户ID传递
12. 新增了多种自定义异常类型,优化了异常映射与错误处理流程
13. 完善了配置热重载逻辑,同步认证凭证与校验器配置
14. 重构了Redis缓存实现,增加了异常捕获与包装
2026-05-31 21:42:03 +08:00

75 lines
2.5 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,
allow_anonymous: bool = False,
) -> None:
self._rate_limiter = rate_limit_port
self._token = token
self._password = password
self._max_attempts = max_attempts
self._lockout_seconds = lockout_seconds
self._allow_anonymous = allow_anonymous
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:
if self._allow_anonymous:
return True, ""
return False, "no credentials configured"
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())