添加后端API和前端项目的初始目录结构,包括应用层模块、工具模块和模型定义 配置前后端的.dockerignore文件以排除开发环境文件 添加前端样式文件,包括字体、Tailwind CSS和主题配置 初始化Python虚拟环境中的类型标记文件
37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from jose import JWTError, jwt
|
|
|
|
from app.config import settings
|
|
from app.models.user import User
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
def create_access_token(user_id: str) -> str:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_expire_minutes)
|
|
to_encode = {"sub": user_id, "exp": expire}
|
|
return jwt.encode(to_encode, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
|
|
|
|
|
|
async def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
) -> User:
|
|
token = credentials.credentials
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm]
|
|
)
|
|
user_id: str = payload.get("sub")
|
|
if user_id is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="无效的认证信息")
|
|
except JWTError:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token已过期或无效")
|
|
|
|
user = await User.get(user_id)
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")
|
|
return user
|