refactor: 更新API路由
- 更新books路由以支持用户认证 - 更新chapters路由以支持用户认证 - 更新conversations路由以支持用户认证 - 更新websocket路由以支持用户认证和连接管理
This commit is contained in:
@@ -3,26 +3,29 @@
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Body
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
import uuid
|
||||
|
||||
from database import get_async_db, Conversation, Segment, User
|
||||
from database.models import Conversation as ConversationModel, Segment as SegmentModel
|
||||
from middleware.auth import get_current_user
|
||||
from database.models import User as UserModel
|
||||
|
||||
router = APIRouter(prefix="/api/conversations", tags=["conversations"])
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_conversation(
|
||||
user_id: str,
|
||||
current_user: UserModel = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
):
|
||||
"""创建新对话"""
|
||||
"""创建新对话(需要认证)"""
|
||||
conversation = ConversationModel(
|
||||
id=str(uuid.uuid4()),
|
||||
user_id=user_id,
|
||||
user_id=current_user.id,
|
||||
started_at=datetime.now(timezone.utc),
|
||||
status="active"
|
||||
)
|
||||
@@ -41,13 +44,18 @@ async def create_conversation(
|
||||
@router.get("/{conversation_id}")
|
||||
async def get_conversation(
|
||||
conversation_id: str,
|
||||
current_user: UserModel = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
):
|
||||
"""获取对话详情"""
|
||||
"""获取对话详情(需要认证,只能访问自己的对话)"""
|
||||
conversation = await db.get(ConversationModel, conversation_id)
|
||||
if not conversation:
|
||||
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||
|
||||
# 验证用户权限
|
||||
if conversation.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="无权访问此对话")
|
||||
|
||||
return {
|
||||
"id": conversation.id,
|
||||
"user_id": conversation.user_id,
|
||||
@@ -64,13 +72,18 @@ async def get_conversation(
|
||||
@router.post("/{conversation_id}/end")
|
||||
async def end_conversation(
|
||||
conversation_id: str,
|
||||
current_user: UserModel = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_async_db)
|
||||
):
|
||||
"""结束对话"""
|
||||
"""结束对话(需要认证,只能结束自己的对话)"""
|
||||
conversation = await db.get(ConversationModel, conversation_id)
|
||||
if not conversation:
|
||||
raise HTTPException(status_code=404, detail="Conversation not found")
|
||||
|
||||
# 验证用户权限
|
||||
if conversation.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="无权操作此对话")
|
||||
|
||||
conversation.status = "ended"
|
||||
conversation.ended_at = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user