c3a5dc2a41
admin_user 加 pages_override(可空 JSON)+ Alembic 迁移;role=="custom" 时可见页由这份逐页 勾选决定,否则跟随角色。create/update 收 pages_override(切回普通角色自动清空),_validate_role 放行 custom 哨兵角色。登录/me 下发有效页时优先用 override → 左侧导航直接按勾选生效。 补 4 个用例覆盖建/改/切回/切入,test_admin_roles 全绿。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
76 lines
2.0 KiB
Python
76 lines
2.0 KiB
Python
"""admin_user 表 CRUD。"""
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.security import hash_password
|
|
from app.models.admin import AdminUser
|
|
|
|
|
|
def get_by_id(db: Session, admin_id: int) -> AdminUser | None:
|
|
return db.get(AdminUser, admin_id)
|
|
|
|
|
|
def get_by_username(db: Session, username: str) -> AdminUser | None:
|
|
stmt = select(AdminUser).where(AdminUser.username == username)
|
|
return db.execute(stmt).scalar_one_or_none()
|
|
|
|
|
|
def create_admin(
|
|
db: Session,
|
|
*,
|
|
username: str,
|
|
password: str,
|
|
role: str = "operator",
|
|
plain_password: str | None = None,
|
|
pages_override: list[str] | None = None,
|
|
) -> AdminUser:
|
|
"""建管理员。plain_password 非空则额外留存明文(后台 UI 建的账号传,供权限管理页复看);
|
|
脚本/起后台建账号不传(留 None → 前端不显示密码)。
|
|
pages_override:role=="custom" 时传专属可见页 key 列表;普通角色为 None。"""
|
|
admin = AdminUser(
|
|
username=username,
|
|
password_hash=hash_password(password),
|
|
role=role,
|
|
plain_password=plain_password,
|
|
pages_override=pages_override,
|
|
)
|
|
db.add(admin)
|
|
db.commit()
|
|
db.refresh(admin)
|
|
return admin
|
|
|
|
|
|
def update_last_login(db: Session, admin: AdminUser) -> None:
|
|
admin.last_login_at = datetime.now(timezone.utc)
|
|
db.commit()
|
|
|
|
|
|
def list_admins(db: Session) -> list[AdminUser]:
|
|
stmt = select(AdminUser).order_by(AdminUser.id)
|
|
return list(db.execute(stmt).scalars().all())
|
|
|
|
|
|
def set_role(db: Session, admin: AdminUser, *, role: str) -> AdminUser:
|
|
admin.role = role
|
|
db.commit()
|
|
db.refresh(admin)
|
|
return admin
|
|
|
|
|
|
def set_status(db: Session, admin: AdminUser, *, status: str) -> AdminUser:
|
|
admin.status = status
|
|
db.commit()
|
|
db.refresh(admin)
|
|
return admin
|
|
|
|
|
|
def set_password(db: Session, admin: AdminUser, *, password: str) -> AdminUser:
|
|
admin.password_hash = hash_password(password)
|
|
db.commit()
|
|
db.refresh(admin)
|
|
return admin
|