Files
syops/backend/app/services/admin/permission_service.py
T
HTEWJ\26070045 ca9c174f29 Merge branch 'dev' into snow
# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	backend/app/services/knowledge_cleaning/dify_sync_service.py
#	backend/app/services/knowledge_cleaning/settings_service.py
#	backend/tests/test_dify_sync_process_rule.py
#	docker-compose.yml
#	docs/funclist.md
#	frontend/package-lock.json
#	frontend/src/config.ts
#	frontend/src/features/admin/components/AdminNav.vue
#	frontend/src/features/admin/constants/modules.ts
#	frontend/src/features/admin/stores/admin-nav.store.ts
#	frontend/src/features/chat/components/messages/ChatMessageBubble.vue
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/auth.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/auth.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/auth.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/auth.json
#	frontend/src/locales/zh-TW/errors.json
2026-09-11 14:55:20 +08:00

162 lines
5.4 KiB
Python

"""
backend/app/services/admin/permission_service.py
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
依赖:models、wecom_notify.send_wecom_event_message。
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.wecom_notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]:
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
return users, agents
def _apply_user_agent_action(user: User, agents: list[Agent], action: str) -> None:
"""对单个用户执行 add / remove / set 权限变更。"""
if action == 'set':
user.agents = agents
elif action == 'add':
for agent in agents:
if agent not in user.agents:
user.agents.append(agent)
elif action == 'remove':
for agent in agents:
if agent in user.agents:
user.agents.remove(agent)
def _notify_batch_permission_update(user: User, agents: list[Agent], action: str) -> None:
"""批量权限变更后向已绑定企微的用户推送通知。"""
if not user.wecom_userid:
return
action_label = _BATCH_ACTION_LABELS.get(action, action)
agent_names = '、'.join([a.name for a in agents]) if agents else '无'
send_wecom_event_message(
event_type='permission_batch_updated',
user=user,
title='应用权限已更新',
content=f'管理员已{action_label}你的应用权限:{agent_names}',
jump_path='/workspace',
)
def batch_update_permissions(data: dict[str, Any]) -> dict:
"""
批量更新多用户的 Agent 权限(add / remove / set)。
Returns:
{ status, updated_count }。
Raises:
ValidationError: 未选择用户。
"""
user_ids = data.get('user_ids', [])
agent_ids = data.get('agent_ids', [])
action = data.get('action', 'add')
if not user_ids:
raise ValidationError('No users selected')
users, agents = _load_users_and_agents(user_ids, agent_ids)
if not agents and action != 'set':
if action == 'remove':
return {'status': 'ok', 'updated_count': 0}
for user in users:
_apply_user_agent_action(user, agents, action)
_notify_batch_permission_update(user, agents, action)
db.session.commit()
return {'status': 'ok', 'updated_count': len(users)}
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
"""
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
Returns:
{ status }。
Raises:
NotFoundError: 用户不存在。
"""
user = db.session.get(User, user_id)
if not user:
raise NotFoundError('Not found')
agent_ids = data.get('agent_ids', [])
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.order_by(PermissionRequest.created_at.desc())
.all()
)
return [serialize_permission_request(r) for r in reqs]
def approve_permission_request(request_id: int) -> dict:
"""
批准权限申请:更新状态并将 Agent 加入用户权限。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
user.agents.append(agent)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_approved',
user=user,
title='权限申请已通过',
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
def reject_permission_request(request_id: int) -> dict:
"""
拒绝权限申请并通知用户(若已绑定企微)。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_rejected',
user=user,
title='权限申请未通过',
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}