auth/ is now an independent package

This commit is contained in:
2026-05-19 22:31:30 +08:00
parent 623fac8749
commit af5f7b38f8
9 changed files with 204 additions and 6 deletions
+54
View File
@@ -0,0 +1,54 @@
import os
from fastapi import APIRouter, Depends, HTTPException, Request
from .deps import get_current_user
from .jwt import create_jwt_token, create_refresh_token, verify_access_token, decode_token
from .oauth import oauth_router
# 创建全局 auth 路由器
router = APIRouter(tags=["Authentication"])
# 挂载第三方 OAuth 的路由器
router.include_router(oauth_router)
# 定义一个动态获取当前完整用户对象的依赖项
# 这样 auth 包不需要知道 User 模型长什么样
# 也不需要知道 SessionLocal 是什么
# 全部由外部动态提供
def get_user_by_id(user_id: str = Depends(get_current_user)):
"""
这是一个占位/契约函数。
我们在 main.py 中可以通过 app.dependency_overrides 或者直接在使用时,
把具体的数据库查询逻辑绑定到这里。
"""
raise NotImplementedError("Please override or inject the implementation of this function in the external `main.py` file.")
@router.get("/me")
def me(current_user = Depends(get_user_by_id)):
"""
current_user 是由外部解析并传进来的完整用户对象(或者是字典)
"""
return current_user
@router.post("/refresh")
def refresh_token(refresh_token: str):
payload = decode_token(refresh_token)
if payload.get("type") != "refresh":
raise HTTPException(status_code=401)
user_id = payload.get("sub")
new_access = create_jwt_token({"sub": user_id})
return {"access_token": new_access}
@router.post("/logout")
def logout():
return {"message": "ok"}
# 显式声明暴露的接口
__all__ = [
"router",
"get_current_user",
"get_user_by_id",
"create_jwt_token",
"create_refresh_token",
"verify_access_token",
]