Files
xiaozhi-esp32-server/main/xiaozhi-server/core/auth.py
T

55 lines
1.7 KiB
Python
Raw Normal View History

2025-02-18 00:07:19 +08:00
from config.logger import setup_logging
2025-02-13 17:06:48 +08:00
2025-02-18 00:07:19 +08:00
TAG = __name__
2025-02-18 00:45:54 +08:00
logger = setup_logging()
2025-02-13 17:06:48 +08:00
2025-02-14 11:33:56 +08:00
2025-02-13 17:06:48 +08:00
class AuthenticationError(Exception):
"""认证异常"""
pass
2025-02-14 11:33:56 +08:00
2025-02-13 17:06:48 +08:00
class AuthMiddleware:
def __init__(self, config):
self.config = config
self.auth_config = config["server"].get("auth", {})
# 构建token查找表
self.tokens = {
2025-02-14 11:33:56 +08:00
item["token"]: item["name"]
2025-02-13 17:06:48 +08:00
for item in self.auth_config.get("tokens", [])
}
# 设备白名单
self.allowed_devices = set(
self.auth_config.get("allowed_devices", [])
)
2025-02-14 11:33:56 +08:00
2025-02-13 17:06:48 +08:00
async def authenticate(self, headers):
"""验证连接请求"""
# 检查是否启用认证
if not self.auth_config.get("enabled", False):
return True
2025-02-14 11:33:56 +08:00
# 检查设备是否在白名单中
device_id = headers.get("device-id", "")
if self.allowed_devices and device_id in self.allowed_devices:
return True
2025-02-13 17:06:48 +08:00
# 验证Authorization header
2025-02-14 11:33:56 +08:00
auth_header = headers.get("authorization", "")
2025-02-13 17:06:48 +08:00
if not auth_header.startswith("Bearer "):
2025-02-18 00:07:19 +08:00
logger.bind(tag=TAG).error("Missing or invalid Authorization header")
2025-02-13 17:06:48 +08:00
raise AuthenticationError("Missing or invalid Authorization header")
2025-02-14 11:33:56 +08:00
2025-02-13 17:06:48 +08:00
token = auth_header.split(" ")[1]
if token not in self.tokens:
2025-02-18 00:07:19 +08:00
logger.bind(tag=TAG).error(f"Invalid token: {token}")
2025-02-13 17:06:48 +08:00
raise AuthenticationError("Invalid token")
2025-02-14 11:33:56 +08:00
2025-02-18 00:07:19 +08:00
logger.bind(tag=TAG).info(f"Authentication successful - Device: {device_id}, Token: {self.tokens[token]}")
2025-02-13 17:06:48 +08:00
return True
2025-02-14 11:33:56 +08:00
2025-02-13 17:06:48 +08:00
def get_token_name(self, token):
"""获取token对应的设备名称"""
return self.tokens.get(token)