Compare commits
2 Commits
b95cce592f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 61e3d71b72 | |||
| d2162f93e0 |
+17
-2
@@ -28,7 +28,7 @@ async def load_members_by_workspace_ids(workspace_ids: List[str]) -> List[List[W
|
||||
|
||||
class CustomContext(BaseContext):
|
||||
def __init__(self, request: Request):
|
||||
super().__init__(request)
|
||||
super().__init__()
|
||||
self.db = SessionLocal()
|
||||
self.request = request
|
||||
self._current_user: Optional[User] = None
|
||||
@@ -41,17 +41,32 @@ class CustomContext(BaseContext):
|
||||
return self._current_user
|
||||
|
||||
try:
|
||||
# 打印 Request Headers,确认 Token 是否真的传过来了
|
||||
# print(f"DEBUG: Auth Headers: {self.request.headers.get('authorization')}")
|
||||
# print(f"DEBUG: Cookies: {self.request.cookies}")
|
||||
# 借用 auth 包的纯工具解出 ID
|
||||
user_id = get_current_user_id(self.request)
|
||||
# print(f"DEBUG: Extracted User ID: {user_id}") # 确认 ID 是否解出
|
||||
|
||||
if not user_id:
|
||||
return None
|
||||
|
||||
# 在 Context 的数据库连接中查询完整用户
|
||||
user = self.db.query(User).filter(User.id == user_id).first()
|
||||
# print(f"DEBUG: DB User Found: {user}") # 确认数据库是否查到
|
||||
|
||||
self._current_user = user
|
||||
return user
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 打印真实的异常信息
|
||||
# print(f"DEBUG: Error in get_current_user: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc() # 打印堆栈
|
||||
return None
|
||||
|
||||
|
||||
async def get_context(request: Request) -> AsyncGenerator[CustomContext, None]:
|
||||
# print("--- NEW GRAPHQL REQUEST RECEIVED ---")
|
||||
context = CustomContext(request)
|
||||
try:
|
||||
yield context
|
||||
|
||||
@@ -11,7 +11,7 @@ class Query:
|
||||
@strawberry.field
|
||||
async def me(self, info: Info[CustomContext, None]) -> Optional[UserType]:
|
||||
# 从 context 获取当前登录用户
|
||||
user = await info.context. xzz()
|
||||
user = await info.context.get_current_user()
|
||||
# Strawberry 会自动将 SQLAlchemy 实例映射为 UserType
|
||||
return user
|
||||
|
||||
|
||||
@@ -4,15 +4,19 @@ from datetime import datetime
|
||||
from strawberry.types import Info
|
||||
|
||||
from app.utils.format import get_image_url
|
||||
from app.models.user import User
|
||||
|
||||
@strawberry.type
|
||||
class UserType:
|
||||
id: str
|
||||
email: str
|
||||
name: str
|
||||
avatar: str
|
||||
handle: Optional[str]
|
||||
|
||||
@strawberry.field
|
||||
def avatar(self, root: User) -> Optional[str]:
|
||||
return root.avatar_url
|
||||
|
||||
# 互动统计字段
|
||||
following_count: int
|
||||
follower_count: int
|
||||
|
||||
@@ -6,6 +6,7 @@ from strawberry.fastapi import GraphQLRouter
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from auth import router as auth_router
|
||||
from app.media.router import router as media_router
|
||||
|
||||
from app.db import engine, SessionLocal
|
||||
from app.models import Base, User
|
||||
@@ -44,6 +45,7 @@ graphql_router = GraphQLRouter(schema, context_getter=get_context)
|
||||
|
||||
# 挂载路由
|
||||
app.include_router(auth_router) # 保留现有的 auth 路由供 Google OAuth 回调使用
|
||||
app.include_router(media_router) # 挂载媒体路由,提供头像代理访问等等
|
||||
app.include_router(graphql_router, prefix="/graphql") # 挂载 GraphQL 终点,前端以后只需要请求 /graphql
|
||||
|
||||
# 打印路由测试
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
import oss2
|
||||
from app.utils.s3 import bucket
|
||||
|
||||
router = APIRouter(prefix="/v1/media", tags=["Media"])
|
||||
|
||||
@router.get("/{file_path:path}")
|
||||
async def get_avatar(file_path: str):
|
||||
"""
|
||||
通过流式传输代理阿里云 OSS 中的图片
|
||||
file_path 接收 avatars/xxx/avatar.jpg 等任何相对路径
|
||||
"""
|
||||
s3_key = file_path.lstrip("/")
|
||||
|
||||
if not s3_key:
|
||||
raise HTTPException(status_code=400, detail="Invalid file path")
|
||||
|
||||
try:
|
||||
# 从阿里云 OSS 获取对象
|
||||
# oss2 的 get_object 是同步阻塞的
|
||||
# 初期可以直接用,后续高并发可以放入 run_in_executor
|
||||
oss_object = bucket.get_object(s3_key)
|
||||
|
||||
# 获取文件的 Content-Type
|
||||
content_type = oss_object.headers.get("Content-Type", "image/jpeg")
|
||||
|
||||
# 创建一个生成器来分块读取 OSS 数据,防止大文件时撑爆内存
|
||||
def image_stream():
|
||||
while True:
|
||||
chunk = oss_object.read(1024 * 64) # 每次读 64KB
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
|
||||
# 流式返回给前端
|
||||
return StreamingResponse(image_stream(), media_type=content_type)
|
||||
|
||||
except oss2.exceptions.NoSuchKey:
|
||||
# 阿里云 OSS 专属的 404 异常
|
||||
raise HTTPException(status_code=404, detail="Image not found in storage")
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise HTTPException(status_code=500, detail="Internal storage service error")
|
||||
@@ -17,6 +17,19 @@ class User(Base, AutoID):
|
||||
handle = Column(String, unique=True, index=True, nullable=True)
|
||||
avatar = Column(String)
|
||||
|
||||
@property
|
||||
def avatar_url(self) -> str | None:
|
||||
if not self.avatar:
|
||||
return None
|
||||
|
||||
# 如果是第三方(如未迁移成功时降级的 Google 原始链接),直接返回
|
||||
if self.avatar.startswith(("http://", "https://")):
|
||||
return self.avatar
|
||||
|
||||
path = self.avatar.lstrip("/")
|
||||
|
||||
return f"/v1/media/{path}"
|
||||
|
||||
# ---- 互动统计字段 ----
|
||||
following_count = Column(Integer, default=0, nullable=False, server_default="0") # 关注了多少人
|
||||
follower_count = Column(Integer, default=0, nullable=False, server_default="0") # 粉丝数
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ def get_current_user_id(request: Request):
|
||||
raise HTTPException(status_code=401, detail="Not authenticated")
|
||||
|
||||
try:
|
||||
payload = decode_token(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
||||
payload = decode_token(token)
|
||||
return payload["sub"]
|
||||
except:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
Reference in New Issue
Block a user