mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-07-22 07:03:53 +08:00
* 🦄 refactor(web): 修改zhikongtaiweb到web * 🦄 refactor: 重写前端 路由守护尚未写完 * 🦄 refactor: 标准化路由 * update:前端重写,保留后端 * update:添加前端代码 * update:pip转成poetry启动 * update:增加mem0ai包依赖 * update:文档增加mem0ai的描述 * feat: play online mp3 (#181) Co-authored-by: 欣南科技 <huangrongzhuang@xin-nan.com> * 修改前端代码 * update:调整项目目录 * update:优化 * update:配置文件去除8002端口 * update:增加开发说明 * update:更新开发协议 --------- Co-authored-by: kalicyh <34980061+kaliCYH@users.noreply.github.com> Co-authored-by: hrz <1710360675@qq.com> Co-authored-by: freshlife001 <talent@mises.site> Co-authored-by: CGD <3030332422@qq.com>
55 lines
1.7 KiB
Python
Executable File
55 lines
1.7 KiB
Python
Executable File
from config.logger import setup_logging
|
|
|
|
TAG = __name__
|
|
logger = setup_logging()
|
|
|
|
|
|
class AuthenticationError(Exception):
|
|
"""认证异常"""
|
|
pass
|
|
|
|
|
|
class AuthMiddleware:
|
|
def __init__(self, config):
|
|
self.config = config
|
|
self.auth_config = config["server"].get("auth", {})
|
|
# 构建token查找表
|
|
self.tokens = {
|
|
item["token"]: item["name"]
|
|
for item in self.auth_config.get("tokens", [])
|
|
}
|
|
# 设备白名单
|
|
self.allowed_devices = set(
|
|
self.auth_config.get("allowed_devices", [])
|
|
)
|
|
|
|
async def authenticate(self, headers):
|
|
"""验证连接请求"""
|
|
# 检查是否启用认证
|
|
if not self.auth_config.get("enabled", False):
|
|
return True
|
|
|
|
# 检查设备是否在白名单中
|
|
device_id = headers.get("device-id", "")
|
|
|
|
if self.allowed_devices and device_id in self.allowed_devices:
|
|
return True
|
|
|
|
# 验证Authorization header
|
|
auth_header = headers.get("authorization", "")
|
|
if not auth_header.startswith("Bearer "):
|
|
logger.bind(tag=TAG).error("Missing or invalid Authorization header")
|
|
raise AuthenticationError("Missing or invalid Authorization header")
|
|
|
|
token = auth_header.split(" ")[1]
|
|
if token not in self.tokens:
|
|
logger.bind(tag=TAG).error(f"Invalid token: {token}")
|
|
raise AuthenticationError("Invalid token")
|
|
|
|
logger.bind(tag=TAG).info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}")
|
|
return True
|
|
|
|
def get_token_name(self, token):
|
|
"""获取token对应的设备名称"""
|
|
return self.tokens.get(token)
|