cmvr-visual/backend/app/services/auth.py

272 lines
11 KiB
Python
Raw Normal View History

import asyncio
from datetime import timedelta
import re
import secrets
from sqlalchemy import delete, select, func, or_
from sqlalchemy.exc import IntegrityError
from app.core.errors import fail
from app.models import Session, User, utcnow
from app.schemas.auth import Login, CreateUser, UserPatch, PasswordChange, UsernameChange
from app.core.security import Actor, token_hash, hash_password, verify_password, validate_password
def user_dto(user):
return {
"id": user.id,
"username": user.username,
"display_name": user.display_name,
"role": user.role,
"disabled": user.disabled,
"must_change_password": user.must_change_password,
}
def validated_username(username):
username = username.strip().lower()
if not re.fullmatch("[a-z0-9_.-]{3,64}", username):
fail(422, "invalid_username", "用户名须为 3–64 位字母、数字、点、横线或下划线")
return username
async def bootstrap_admin(db, settings):
if not settings.admin_username and (not settings.admin_password):
return
if not settings.admin_username or not settings.admin_password:
raise ValueError("Both ADMIN_USERNAME and ADMIN_PASSWORD are required for bootstrap")
validate_password(settings.admin_password, minimum=6)
async with db.session() as session:
# 管理员可以改名;停用管理员也不能触发旧账号重建或恢复初始密码。
# 同时保留配置同名普通用户的保护,不覆盖原账号或把它提升为管理员。
exists = await session.scalar(
select(User.id)
.where(
or_(User.role == "admin", User.username == settings.admin_username.strip().lower())
)
.limit(1)
)
if exists is not None:
return
session.add(
User(
username=settings.admin_username.strip().lower(),
display_name=settings.admin_display_name,
role="admin",
must_change_password=True,
password_hash=await asyncio.to_thread(hash_password, settings.admin_password),
)
)
await session.commit()
async def login(body: Login, runtime):
async with runtime.db.session() as session:
user = await session.scalar(
select(User).where(User.username == body.username.strip().lower())
)
valid = await asyncio.to_thread(
verify_password, body.password, user.password_hash if user else ""
)
if not valid or user is None or user.disabled:
fail(401, "invalid_credentials", "用户名或密码不正确")
token, csrf = (secrets.token_urlsafe(32), secrets.token_urlsafe(32))
settings = runtime.settings
session.add(
Session(
token_hash=token_hash(token),
user_id=user.id,
csrf_token=csrf,
expires_at=utcnow() + timedelta(hours=settings.session_hours),
)
)
await session.commit()
return {"user": user_dto(user), "csrf_token": csrf}, token
async def me(actor: Actor = None):
return {
"user": {
"id": actor.id,
"username": actor.username,
"display_name": actor.display_name,
"role": actor.role,
"must_change_password": actor.must_change_password,
},
"csrf_token": actor.csrf_token,
}
async def logout(runtime, actor: Actor = None):
async with runtime.db.session() as session:
await session.execute(delete(Session).where(Session.token_hash == actor.token_hash))
await session.commit()
return None
async def require_session_user(session, actor):
if actor.auth_kind != "session":
fail(403, "session_required", "此操作需要登录会话")
# 鉴权依赖与业务事务之间可能发生停用、改密或重新登录,写入前复核真实会话。
user = await session.scalar(
select(User)
.join(Session, Session.user_id == User.id)
.where(
User.id == actor.id,
User.disabled.is_(False),
Session.token_hash == actor.token_hash,
Session.expires_at > utcnow(),
)
.with_for_update()
)
if user is None:
fail(401, "session_expired", "登录已失效,请重新登录")
return user
async def require_admin_session(session, actor):
user = await require_session_user(session, actor)
if user.role != "admin":
fail(403, "admin_required", "此操作仅限管理员")
return user
async def create_user(body: CreateUser, runtime, actor: Actor = None):
if actor.role != "admin" or actor.auth_kind != "session":
fail(403, "admin_required", "此操作仅限管理员")
username = validated_username(body.username)
validate_password(body.password, minimum=6)
async with runtime.db.session() as session:
await require_admin_session(session, actor)
user = User(
username=username,
display_name=body.display_name.strip() or username,
password_hash=await asyncio.to_thread(hash_password, body.password),
)
session.add(user)
try:
await session.commit()
except IntegrityError:
fail(409, "username_exists", "用户名已存在")
return user_dto(user)
async def list_users(runtime, page: int = 1, page_size: int = 24, actor: Actor = None):
if actor.role != "admin" or actor.auth_kind != "session":
fail(403, "admin_required", "Administrator session required")
if page < 1 or not 1 <= page_size <= 100:
fail(422, "invalid_page", "Invalid page")
async with runtime.db.session() as session:
await require_admin_session(session, actor)
total = await session.scalar(select(func.count()).select_from(User))
rows = (
await session.scalars(
select(User)
.order_by(User.created_at, User.id)
.offset((page - 1) * page_size)
.limit(page_size)
)
).all()
return {
"items": [user_dto(u) for u in rows],
"total": total,
"page": page,
"page_size": page_size,
}
async def patch_user(user_id: str, body: UserPatch, runtime, actor: Actor = None):
if actor.role != "admin" or actor.auth_kind != "session":
fail(403, "admin_required", "此操作仅限管理员")
from app.models import Job, WorkflowRun, Batch
from app.domain.tasks import TERMINAL, RUN_TERMINAL
from app.services.events import emit_job
from app.services.workflows import emit_run
from app.services.batches import emit_batch
async with runtime.db.session() as session:
await require_admin_session(session, actor)
user = await session.scalar(select(User).where(User.id == user_id).with_for_update())
if not user:
fail(404, "user_not_found", "用户不存在")
if body.disabled and user_id == actor.id:
fail(409, "self_disable", "不能禁用当前登录账号")
if body.disabled and user.role == "admin" and not user.disabled:
count = await session.scalar(
select(func.count())
.select_from(User)
.where(User.role == "admin", User.disabled.is_(False))
)
if count <= 1:
fail(409, "last_admin", "不能禁用最后一个管理员")
if body.display_name is not None:
user.display_name = body.display_name.strip() or user.display_name
if body.disabled is not None:
user.disabled = body.disabled
if body.disabled:
await session.execute(delete(Session).where(Session.user_id == user_id))
# 禁用是可恢复的:令牌由鉴权层的 disabled 检查阻断,不能在这里永久撤销。
for model, terminal, emit in (
(Job, TERMINAL, emit_job),
(WorkflowRun, RUN_TERMINAL, emit_run),
(Batch, {"succeeded", "cancelled", "completed_with_errors"}, emit_batch),
):
query = select(model).where(model.owner_id == user_id, model.deleted_at.is_(None))
if body.disabled:
query = query.where(model.state.notin_(terminal))
for record in (await session.scalars(query)).all():
reasons = set(record.hold_reasons or [])
updated = (
reasons | {"admin_suspend"}
if body.disabled
else reasons - {"admin_suspend"}
)
if reasons == updated:
continue
# 只恢复管理员禁用引入的暂停,保留用户手动暂停、批量时段等约束。
record.hold_reasons = sorted(updated)
if (
not body.disabled
and isinstance(record, WorkflowRun)
and (record.error_json or {}).get("code") == "owner_disabled"
):
record.error_json = None
await emit(session, record)
await session.commit()
result = user_dto(user)
runtime.coordinator.wake()
return result
async def change_password(body: PasswordChange, runtime, actor: Actor = None):
if actor.auth_kind != "session":
fail(403, "session_required", "Session required")
validate_password(body.new_password)
async with runtime.db.session() as session:
user = await require_session_user(session, actor)
if not await asyncio.to_thread(verify_password, body.current_password, user.password_hash):
fail(403, "invalid_password", "当前密码不正确")
user.password_hash = await asyncio.to_thread(hash_password, body.new_password)
user.must_change_password = False
await session.execute(delete(Session).where(Session.user_id == actor.id))
await session.commit()
return {"requires_relogin": True}
async def change_username(body: UsernameChange, runtime, actor: Actor = None):
if actor.auth_kind != "session":
fail(403, "session_required", "此操作需要登录会话")
username = validated_username(body.username)
async with runtime.db.session() as session:
user = await require_session_user(session, actor)
if not await asyncio.to_thread(verify_password, body.current_password, user.password_hash):
fail(403, "invalid_password", "当前密码不正确")
if username == user.username:
return user_dto(user)
# 资源与会话绑定稳定的用户 ID;改名仅更新用户名,唯一约束处理并发占名。
user.username = username
try:
await session.commit()
except IntegrityError:
await session.rollback()
fail(409, "username_exists", "用户名已存在")
return user_dto(user)