import hmac from fastapi import Depends, Request from sqlalchemy import select from app.models import Session, User, utcnow, ApiToken from app.core.errors import fail from app.core.security import Actor, COOKIE, token_hash async def current_actor(request: Request): authorization = request.headers.get("Authorization", "") if authorization.startswith("Bearer "): return await bearer_actor(request, authorization[7:]) token = request.cookies.get(COOKIE) if not token or len(token) > 512: fail(401, "not_authenticated", "请先登录") async with request.app.state.db.session() as session: row = ( await session.execute( select(Session, User) .join(User, User.id == Session.user_id) .where( Session.token_hash == token_hash(token), Session.expires_at > utcnow(), User.disabled.is_(False), ) ) ).first() if row is None: fail(401, "session_expired", "登录已失效,请重新登录") saved, user = row return Actor( user.id, user.username, user.display_name, user.role, saved.csrf_token, saved.token_hash, must_change_password=user.must_change_password, ) async def csrf_actor(request: Request, actor: Actor = Depends(current_actor)): if actor.auth_kind == "bearer": if request.headers.get("sec-fetch-site") or request.cookies.get(COOKIE): fail(403, "machine_token_only", "Use session authentication in browsers") return actor supplied = request.headers.get("X-CSRF-Token", "") if not hmac.compare_digest(supplied.encode("utf-8"), actor.csrf_token.encode("utf-8")): fail(403, "csrf_failed", "请求校验失败,请刷新登录状态") # Same-origin proxy is the deployment default; reject explicitly cross-site writes. if request.headers.get("sec-fetch-site") == "cross-site": fail(403, "cross_site_request", "不允许跨站写入") return actor async def bearer_actor(request, token): async with request.app.state.db.session() as session: row = await session.scalar( select(ApiToken).where( ApiToken.token_hash == token_hash(token), ApiToken.revoked_at.is_(None) ) ) if not row or (row.expires_at and row.expires_at <= utcnow()): fail(401, "token_expired", "Token unavailable") user = await session.get(User, row.owner_id) if not user or user.disabled: fail(401, "token_expired", "Token unavailable") path = request.url.path.removeprefix("/api/").split("/")[0] if path == "submissions": operation = request.query_params.get("operation", "") path = ( "assets" if operation in {"assets.publish", "shared.import"} else "workflows" if operation.startswith("workflow") or operation.startswith("story.") or operation.startswith("editor.") else "batches" if operation.startswith("batch") else "jobs" ) scope = { "workflow-runs": "workflows", "stories": "workflows", "editors": "workflows", "shared-assets": "assets", }.get(path, path) + (":read" if request.method in {"GET", "HEAD"} else ":write") if scope not in row.scopes: fail(403, "scope_required", "Token scope required: " + scope) return Actor( user.id, user.username, user.display_name, "user", "", row.token_hash, "bearer", row.scopes, user.must_change_password, )