增加鉴权系统

This commit is contained in:
2026-07-03 21:31:25 +08:00
parent 8073dd63a7
commit 7e65fadd83
12 changed files with 301 additions and 20 deletions
+23 -3
View File
@@ -23,8 +23,8 @@ class JsonSessionStorage:
def __init__(self, data_dir: Path) -> None:
self.data_dir = data_dir
async def create(self, system_prompt: str) -> Session:
return await asyncio.to_thread(self._create, system_prompt)
async def create(self, system_prompt: str, user_id: str | None = None) -> Session:
return await asyncio.to_thread(self._create, system_prompt, user_id)
async def read(self, session_id: str) -> Session:
return await asyncio.to_thread(self._read, session_id)
@@ -32,6 +32,9 @@ class JsonSessionStorage:
async def write(self, session: Session) -> None:
await asyncio.to_thread(self._write, session)
async def list_by_user(self, user_id: str) -> list[Session]:
return await asyncio.to_thread(self._list_by_user, user_id)
def _path(self, session_id: str) -> Path:
try:
normalized = str(UUID(session_id))
@@ -39,12 +42,13 @@ class JsonSessionStorage:
raise SessionNotFoundError(session_id) from exc
return self.data_dir / f"{normalized}.json"
def _create(self, system_prompt: str) -> Session:
def _create(self, system_prompt: str, user_id: str | None) -> Session:
try:
self.data_dir.mkdir(parents=True, exist_ok=True)
while True:
now = datetime.now(UTC)
session = Session(
user_id=user_id,
session_id=str(uuid4()),
system_prompt=system_prompt,
created_at=now,
@@ -75,6 +79,22 @@ class JsonSessionStorage:
except (OSError, json.JSONDecodeError, ValidationError) as exc:
raise SessionStorageError("could not read session") from exc
def _list_by_user(self, user_id: str) -> list[Session]:
sessions: list[Session] = []
try:
for path in self.data_dir.glob("*.json"):
try:
UUID(path.stem)
except ValueError:
continue
with path.open(encoding="utf-8") as file:
session = Session.model_validate(json.load(file))
if session.user_id == user_id:
sessions.append(session)
except (OSError, json.JSONDecodeError, ValidationError) as exc:
raise SessionStorageError("could not list sessions") from exc
return sessions
def _write(self, session: Session) -> None:
path = self._path(session.session_id)
if not path.exists():