第一次提交
This commit is contained in:
3
backend/app/modules/auth/__init__.py
Normal file
3
backend/app/modules/auth/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from app.modules.auth.router import router
|
||||
|
||||
__all__ = ["router"]
|
||||
20
backend/app/modules/auth/deps.py
Normal file
20
backend/app/modules/auth/deps.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
|
||||
from app.db.platform_store import get_platform_store
|
||||
from app.modules.auth.service import decode_access_token
|
||||
|
||||
|
||||
def get_current_user(authorization: str | None = Header(default=None)) -> dict:
|
||||
"""从 Bearer 令牌解析出当前登录用户,供受保护接口依赖使用。"""
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少认证令牌")
|
||||
token = authorization.split(" ", 1)[1].strip()
|
||||
user_id = decode_access_token(token)
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="令牌无效或已过期")
|
||||
user = get_platform_store().user_by_id(user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")
|
||||
return user
|
||||
30
backend/app/modules/auth/router.py
Normal file
30
backend/app/modules/auth/router.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.db.platform_store import get_platform_store
|
||||
from app.modules.auth.deps import get_current_user
|
||||
from app.modules.auth.service import create_access_token
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(body: LoginBody) -> dict:
|
||||
user = get_platform_store().login(body.username, body.password)
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户名或密码错误")
|
||||
token = create_access_token(user["id"])
|
||||
return {"code": 0, "message": "ok", "data": {"token": token, "user": user}}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(current_user: dict = Depends(get_current_user)) -> dict:
|
||||
return {"code": 0, "message": "ok", "data": current_user}
|
||||
33
backend/app/modules/auth/service.py
Normal file
33
backend/app/modules/auth/service.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import jwt
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def create_access_token(user_id: str, expires_minutes: int | None = None) -> str:
|
||||
"""为指定用户签发 JWT 访问令牌。"""
|
||||
settings = get_settings()
|
||||
expire = _now() + timedelta(minutes=expires_minutes or settings.access_token_expire_minutes)
|
||||
payload = {
|
||||
"sub": user_id,
|
||||
"iat": int(_now().timestamp()),
|
||||
"exp": int(expire.timestamp()),
|
||||
}
|
||||
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> str | None:
|
||||
"""校验并返回令牌中的用户 ID;无效/过期返回 None。"""
|
||||
settings = get_settings()
|
||||
try:
|
||||
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
|
||||
except jwt.PyJWTError:
|
||||
return None
|
||||
sub = payload.get("sub")
|
||||
return sub if isinstance(sub, str) else None
|
||||
Reference in New Issue
Block a user