Files

202 lines
9.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/models/user.py
用途:用户账户、首页偏好、登录审计相关模型。
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
"""
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from sqlalchemy import DateTime, ForeignKey, JSON, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from werkzeug.security import check_password_hash, generate_password_hash
from app.models.base import Base, user_agent_permissions
class UserHomepageConfig(Base):
"""用户首页布局配置。"""
__tablename__ = 'user_homepage_configs'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
layout: Mapped[dict] = mapped_column(JSON, default={})
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class UserFavoriteAgent(Base):
"""用户收藏的 Agent。"""
__tablename__ = 'user_favorite_agents'
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class UserDefaultAgent(Base):
"""用户嵌入首页的默认 Agent(最多 2 个)。"""
__tablename__ = 'user_default_agents'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
sort_order: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
class User(Base):
"""系统用户:认证、RBAC、企微绑定、个人资料。"""
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
email: Mapped[str] = mapped_column(String(100), unique=True)
department: Mapped[Optional[str]] = mapped_column(String(100))
role: Mapped[str] = mapped_column(String(64), default='user')
status: Mapped[str] = mapped_column(String(20), default='active')
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
real_name: Mapped[Optional[str]] = mapped_column(String(50))
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
agents: Mapped[List['Agent']] = relationship(
secondary=user_agent_permissions,
back_populates='users',
)
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
training_records: Mapped[List['TrainingRecord']] = relationship(
'TrainingRecord',
back_populates='user',
)
def _role_default_feature_permissions(self) -> dict[str, bool]:
"""
返回未配置权限组时的功能权限默认值。
核心逻辑:只认 is_platform_admin;不再用 hr / maintenance_manager 角色名暗示能力。
"""
admin = self.is_platform_admin()
return {
'training_hr_manage': admin,
'shipping_notice_force_create': admin,
'shipping_notice.audit_sensitive_read': admin,
'shipping_notice.xfa_split_rule_edit': admin,
'shipping_notice.xfa_split_rule_preview': admin,
'shipping_notice.xfa_split_rule_publish': admin,
'maintenance.ledger_write': admin,
}
def is_platform_admin(self) -> bool:
"""当前用户是否属于平台管理权限组。"""
from app.services.permission_roles.service import user_is_platform_admin
return user_is_platform_admin(self)
def get_feature_permissions(self) -> dict[str, bool]:
"""
返回当前用户的有效功能权限。
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
输出约束:仅返回布尔型权限键。
"""
from app.services.permission_roles.service import effective_feature_permissions
packaged = effective_feature_permissions(self)
if packaged is not None:
return packaged
defaults = self._role_default_feature_permissions()
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
result: dict[str, bool] = {}
for key, default_value in defaults.items():
if key in raw:
result[key] = bool(raw.get(key))
else:
result[key] = bool(default_value)
return result
def set_feature_permissions(self, permissions: dict | None) -> None:
"""
保存用户显式配置的功能权限覆盖项。
用途:给管理后台用户编辑表单落库权限配置。
核心逻辑:只持久化与默认值不同的权限。未种子权限组时默认仅平台管理员全开;其余角色靠 JSON 覆盖或权限组能力键。合同付款预警改走 Agent 授权,不再占用功能权限键。
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
"""
defaults = self._role_default_feature_permissions()
raw = permissions if isinstance(permissions, dict) else {}
overrides: dict[str, bool] = {}
for key, default_value in defaults.items():
if key not in raw:
continue
normalized = bool(raw.get(key))
if normalized != bool(default_value):
overrides[key] = normalized
self.feature_permissions = overrides
def has_feature_permission(self, permission_key: str) -> bool:
"""判断当前用户是否具备指定功能权限。"""
return bool(self.get_feature_permissions().get(permission_key))
def can_manage_training(self) -> bool:
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
return self.has_feature_permission('training_hr_manage')
def client_auth_fields(self) -> dict:
"""登录态/首页共用的角色与功能权限字段。"""
from app.services.permission_roles.service import list_role_name_map
names = list_role_name_map()
return {
'is_platform_admin': self.is_platform_admin(),
'role_name': names.get(self.role) or self.role,
'feature_permissions': self.get_feature_permissions(),
}
def set_password(self, password: str) -> None:
"""设置密码哈希。"""
self.password_hash = generate_password_hash(password)
def check_password(self, password: str) -> bool:
"""校验明文密码是否匹配。"""
if not self.password_hash:
return False
return check_password_hash(self.password_hash, password)
class LoginAudit(Base):
"""登录审计:密码 / 企微登录结果。"""
__tablename__ = 'login_audits'
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
source: Mapped[str] = mapped_column(String(20), default='password')
status: Mapped[str] = mapped_column(String(20), default='success')
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)