feat: initial MVP - FastAPI backend + Vue3 frontend + docker-compose
- backend: FastAPI + SQLAlchemy 2.0(async) + asyncpg + Alembic - 7 API routes: auth/me/articles/sources/bookmarks/subscriptions/admin - models: User/Source/Article/Bookmark/Subscription/ApiToken - services: RSS fetcher (feedparser) + Tencent TMT translator with quota + cache + local NLLB fallback - workers: APScheduler + asyncio pipeline (fetch -> dedupe -> insert -> translate) - seed scripts: create_user, seed_sources (5 RSS: Reuters/BBC/Al Jazeera/NHK/DW) - frontend: Vue 3 + Vite + Naive UI + Pinia + vue-router - pages: Login, Feed (24h), ArticleDetail, Sources, Bookmarks, AdminSources - deploy: docker-compose (postgres/redis/api/worker/frontend/caddy) - docs: README, DEPLOY, architecture, acceptance
This commit is contained in:
77
backend/app/core/deps.py
Normal file
77
backend/app/core/deps.py
Normal file
@@ -0,0 +1,77 @@
|
||||
"""通用依赖:获取当前用户、要求 owner。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from jwt.exceptions import InvalidTokenError
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decode_token, hash_api_token
|
||||
from app.database import get_session
|
||||
from app.models.api_token import ApiToken
|
||||
from app.models.user import User, UserRole
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def _resolve_user(
|
||||
creds: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> User:
|
||||
if creds is None or not creds.credentials:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing credentials")
|
||||
|
||||
token = creds.credentials
|
||||
|
||||
# 1) 先试 API Token(sha256 比较)
|
||||
h = hash_api_token(token)
|
||||
api_row = (
|
||||
await session.execute(
|
||||
select(ApiToken).where(ApiToken.token_hash == h, ApiToken.revoked_at.is_(None))
|
||||
)
|
||||
.scalars()
|
||||
.first()
|
||||
)
|
||||
if api_row:
|
||||
if api_row.expires_at and api_row.expires_at < datetime.now(timezone.utc):
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Token expired")
|
||||
user = (
|
||||
await session.execute(select(User).where(User.id == api_row.user_id))
|
||||
.scalars()
|
||||
.first()
|
||||
)
|
||||
if user and user.is_active:
|
||||
api_row.last_used_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
return user
|
||||
|
||||
# 2) 试 JWT
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
if payload.get("type") != "access":
|
||||
raise InvalidTokenError("wrong type")
|
||||
uid = int(payload["sub"])
|
||||
except (InvalidTokenError, KeyError, ValueError):
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token")
|
||||
|
||||
user = (
|
||||
await session.execute(select(User).where(User.id == uid, User.is_active.is_(True)))
|
||||
.scalars()
|
||||
.first()
|
||||
)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "User not found or inactive")
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_user(user: User = Depends(_resolve_user)) -> User:
|
||||
return user
|
||||
|
||||
|
||||
async def require_owner(user: User = Depends(get_current_user)) -> User:
|
||||
if user.role != UserRole.OWNER:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "Owner only")
|
||||
return user
|
||||
Reference in New Issue
Block a user