"""Additive authorization: public + enabled roles + individual grants. The legacy permission table remains an independent source. New grants are never materialized into it, so revocation cannot erase an owner's existing access. """ from django.core.exceptions import ValidationError as DjangoValidationError import re from django.db.models import Q from django.db import transaction from django.utils import timezone from rest_framework.exceptions import PermissionDenied, ValidationError from system_manage.models.platform_access import PlatformRole, PlatformRoleMember, PlatformGrant MODULES = {'application': 'AI应用', 'mindmap': '思维导图', 'knowledge': '知识库', 'tool': '工具管理', 'model': '模型管理'} FEATURES = {'document_parse': '文档解析'} ACTIONS = {'VIEW': '查看', 'USE': '使用', 'EDIT': '编辑', 'AUTHORIZE': '授权'} DEFAULT_ROLE_ID = '00000000-0000-0000-0000-000000000001' ADMIN_ROLE_ID = '00000000-0000-0000-0000-000000000002' BUILTIN_ADMIN_USER_ID = 'f0dd8f71-e4ee-11ee-8c84-a8a1595801ab' def is_admin(user): return PlatformRoleMember.objects.filter(user_id=user.id, role_id=ADMIN_ROLE_ID, role__enabled=True).exists() @transaction.atomic def reconcile_builtin_roles(): """One-time upgrade: import existing administrators without changing grants. Safe to repeat; only the initial creation imports legacy account types. After that memberships are authoritative, including after demotion. """ from users.models import User PlatformRole.objects.get_or_create(id=DEFAULT_ROLE_ID, defaults={ 'name': '普通用户', 'description': '新激活用户自动关联', 'is_default': True, 'modules': ['knowledge', 'mindmap']}) admin_role, created = PlatformRole.objects.get_or_create(id=ADMIN_ROLE_ID, defaults={ 'name': '系统管理员', 'description': '拥有全部平台管理权限', 'modules': list(MODULES)}) if created: PlatformRoleMember.objects.bulk_create([ PlatformRoleMember(role=admin_role, user_id=pk) for pk in User.objects.filter(role='ADMIN').values_list('id', flat=True) ], ignore_conflicts=True) return {'admin_role_created': created, 'admin_members': PlatformRoleMember.objects.filter(role=admin_role).count()} def _sync_legacy_role(user, operator_id=None): """Keep old integrations as projections of the unified memberships.""" from users.models import UserRoleAssignment from users.serializers.user_manage_ext import invalidate_user_auth_cache from users.serializers.user import update_user_role role = 'ADMIN' if is_admin(user) else 'USER' user.role = role user.save(update_fields=['role', 'update_time']) UserRoleAssignment.objects.filter(user_id=user.id, workspace_id='default', role_id__in=['ADMIN', 'USER']).delete() UserRoleAssignment.objects.create(user_id=user.id, role_id=role, workspace_id='default', granted_by_id=operator_id) if str(user.id) != BUILTIN_ADMIN_USER_ID: update_user_role({'role_setting': [{'role_id': role, 'workspace_ids': ['None' if role == 'ADMIN' else 'default']}]}, user, operator_id) # Clear immediately for callers in this transaction and again after commit # to avoid another request repopulating caches with the previous state. invalidate_user_auth_cache(user.id) transaction.on_commit(lambda: invalidate_user_auth_cache(user.id)) @transaction.atomic def assign_roles(user_id, role_ids, operator_id=None): from users.models import User # All membership writers lock this row first, including bulk role editing. PlatformRole.objects.select_for_update().get(pk=ADMIN_ROLE_ID) user = User.objects.select_for_update().get(pk=user_id) ids = {str(pk) for pk in role_ids} | {DEFAULT_ROLE_ID} roles = list(PlatformRole.objects.select_for_update().filter(pk__in=ids).order_by('id')) if len(roles) != len(ids): raise ValidationError('角色不存在') if str(user.id) == BUILTIN_ADMIN_USER_ID and ADMIN_ROLE_ID not in ids: raise ValidationError('不能移除内置管理员角色') if is_admin(user) and ADMIN_ROLE_ID not in ids and not PlatformRoleMember.objects.filter( role_id=ADMIN_ROLE_ID, user__is_active=True).exclude(user_id=user.id).exists(): raise ValidationError('至少保留一名启用的系统管理员') PlatformRoleMember.objects.filter(user=user).exclude(role_id__in=ids).delete() existing = {str(pk) for pk in user.platform_roles.values_list('role_id', flat=True)} PlatformRoleMember.objects.bulk_create([PlatformRoleMember(user=user, role_id=pk) for pk in ids - existing]) _sync_legacy_role(user, operator_id) return user def assign_legacy_role(user, role_id, operator_id=None): """Adapter for registration and older clients; preserves custom roles.""" if role_id not in ('ADMIN', 'USER'): raise ValidationError('角色不合法') ids = {str(pk) for pk in user.platform_roles.values_list('role_id', flat=True)} ids.discard(ADMIN_ROLE_ID) if role_id == 'ADMIN': ids.add(ADMIN_ROLE_ID) return assign_roles(user.id, ids, operator_id) def require_admin(user): if not is_admin(user): raise PermissionDenied('仅管理员可管理角色和授权') def roles_for(user): return PlatformRole.objects.filter(enabled=True).filter(Q(is_default=True) | Q(members__user_id=user.id)).distinct() def grants_for(user): if not user.is_active: return PlatformGrant.objects.none() role_ids = [str(pk) for pk in roles_for(user).values_list('id', flat=True)] return PlatformGrant.objects.filter(workspace_id='default').exclude(resource_type='FEATURE').filter( Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now()) ).filter(Q(subject_type='ALL') | Q(subject_type='USER', subject_id=str(user.id)) | Q(subject_type='ROLE', subject_id__in=role_ids)) def expand_actions(actions): result = set(actions) if 'EDIT' in result: result |= {'VIEW', 'USE'} if 'USE' in result or 'AUTHORIZE' in result: result.add('VIEW') return result def resource_actions(user, resource_type, target, workspace='default'): if not user.is_active or workspace != 'default': return set() if is_admin(user): return set(ACTIONS) actions = set() for grant in grants_for(user).filter(resource_type=resource_type, target=str(target)): actions.update(grant.actions) return expand_actions(actions) def module_list(user): from system_manage.models import UserMenuSetting if is_admin(user): return list(MODULES) result = set() for role in roles_for(user): result.update(role.modules) # Preserve explicit legacy user menus; no implicit fallback grants once roles exist. setting = UserMenuSetting.objects.filter(user_id=user.id).first() if setting: result.update(setting.menu_list or []) for grant in grants_for(user).filter(resource_type='MODULE'): if 'VIEW' in expand_actions(grant.actions): result.add(grant.target) return [key for key in MODULES if key in result] def check_feature_request(request, user): """Backend counterpart to menu visibility for business write operations. Read endpoints remain available for cross-module resource selectors; their existing resource permission checks still apply. """ if is_admin(user) or request.method in ('GET', 'HEAD', 'OPTIONS'): return match = re.search(r'/workspace/default/(knowledge|application|tool|model)(?:/|$)', request.path) if match and match.group(1) not in module_list(user): from common.exception.app_exception import AppUnauthorizedFailed raise AppUnauthorizedFailed(403, '未授权使用该功能') def permission_strings(user): """Expand new grants to the original endpoint permission vocabulary. Do not emit bare resource markers: legacy endpoints treat those as full management. AUTHORIZE is separate from EDIT. """ from common.constants.permission_constants import (PermissionConstants, Resource, ResourcePermission, ResourcePermissionGroup, get_permission_list_by_resource_group) result = set() for grant in grants_for(user).exclude(resource_type='MODULE'): if grant.resource_type not in ('KNOWLEDGE', 'APPLICATION', 'TOOL', 'MODEL'): continue actions = expand_actions(grant.actions) scope = f':/WORKSPACE/default/{grant.resource_type}/{grant.target}' for level in ('VIEW', 'MANAGE'): if level == 'VIEW' and 'VIEW' not in actions: continue if level == 'MANAGE' and 'EDIT' not in actions: continue group = ResourcePermissionGroup(Resource(grant.resource_type), ResourcePermission(level)) for permission in get_permission_list_by_resource_group(group): name = str(permission) # Member/grant management requires AUTHORIZE, even for editors. if any(part in name for part in ('WORKSPACE_USER_RESOURCE_PERMISSION', '+AUTH', '+ADD_MEMBER', '+REMOVE_MEMBER')): continue result.add(name + scope) if 'AUTHORIZE' in actions: for permission in PermissionConstants: name = str(permission.value) if name.startswith(grant.resource_type + '_WORKSPACE_USER_RESOURCE_PERMISSION:') or name.startswith(grant.resource_type + ':READ+AUTH'): result.add(name + scope) return result def resource_models(): from application.models import Application from knowledge.models import Knowledge from tools.models import Tool from models_provider.models import Model from system_manage.models.ai_hub import AIParserResource, AIService return {'KNOWLEDGE': Knowledge, 'APPLICATION': Application, 'TOOL': Tool, 'MODEL': Model, 'PARSER': AIParserResource, 'SERVICE': AIService} def catalog(): resources = [] for kind, model in resource_models().items(): fields = ['id', 'name'] + (['provider', 'model_type'] if kind == 'MODEL' else []) query = model.objects.filter(workspace_id='default') if kind == 'KNOWLEDGE': query = query.exclude(meta__has_key='_version_snapshot') for item in query.values(*fields).order_by('name'): resources.append({**item, 'id': str(item['id']), 'resource_type': kind}) return resources def validate_target(resource_type, target): if resource_type == 'MODULE': if target not in MODULES: raise ValidationError('功能无效') elif resource_type == 'FEATURE': if target not in FEATURES: raise ValidationError('功能无效') else: model = resource_models().get(resource_type) try: valid = model is not None and model.objects.filter(pk=target, workspace_id='default').exists() if valid and resource_type == 'KNOWLEDGE': valid = not model.objects.filter(pk=target, meta__has_key='_version_snapshot').exists() except (ValueError, TypeError, DjangoValidationError): valid = False if not valid: raise ValidationError('资源不存在') def effective_detail(user): """Explain every source; legacy entries remain identifiable and revocable.""" from system_manage.models import WorkspaceUserResourcePermission, UserMenuSetting role_names = {str(r.id): r.name for r in roles_for(user)} rows = [] for grant in grants_for(user): rows.append({'resource_type': grant.resource_type, 'target': grant.target, 'actions': sorted(expand_actions(grant.actions)), 'source': '所有用户' if grant.subject_type == 'ALL' else ( role_names.get(grant.subject_id, '角色') if grant.subject_type == 'ROLE' else '单独授权'), 'expires_at': grant.expires_at}) for role in roles_for(user): rows.extend({'resource_type': 'MODULE', 'target': module, 'actions': ['VIEW'], 'source': role.name} for module in role.modules) legacy_menu = UserMenuSetting.objects.filter(user_id=user.id).first() if legacy_menu: rows.extend({'resource_type': 'MODULE', 'target': m, 'actions': ['VIEW'], 'source': '原用户菜单授权'} for m in legacy_menu.menu_list) for grant in WorkspaceUserResourcePermission.objects.filter(user_id=user.id, workspace_id='default'): actions = ['VIEW', 'USE'] if 'VIEW' in grant.permission_list else [] if 'MANAGE' in grant.permission_list or 'ROLE' in grant.permission_list: actions = list(ACTIONS) rows.append({'resource_type': grant.auth_target_type, 'target': grant.target, 'actions': actions, 'source': '原用户资源授权'}) for row in authorization_rows(): if row.get('readonly') and ((row['subject_type'] == 'ROLE' and row['subject_id'] in role_names) or (row['subject_type'] == 'USER' and row['subject_id'] == str(user.id))): rows.append({**row, 'source': role_names.get(row['subject_id'], '原用户菜单授权') + '(菜单附带)'}) for kind in ('PARSER', 'SERVICE'): model = resource_models()[kind] for obj in model.objects.filter(workspace_id='default').filter(Q(owner_id=user.id) | Q(allowed_users__contains=[str(user.id)])): owner = str(obj.owner_id) == str(user.id) rows.append({'resource_type': kind, 'target': str(obj.id), 'actions': list(ACTIONS) if owner else ['VIEW', 'USE'], 'source': '资源所有者' if owner else '原用户资源授权'}) return {'modules': module_list(user), 'roles': [{'id': k, 'name': v} for k, v in role_names.items()], 'permissions': rows, 'is_admin': is_admin(user)} def authorization_rows(): """Expose compatibility grants in the same management list, without migration.""" from system_manage.models import UserMenuSetting, WorkspaceUserResourcePermission rows = list(PlatformGrant.objects.values('id', 'subject_type', 'subject_id', 'resource_type', 'target', 'actions', 'expires_at')) for role in PlatformRole.objects.exclude(id=ADMIN_ROLE_ID): rows.extend({'id': f'role-menu:{role.id}:{m}', 'subject_type': 'ROLE', 'subject_id': str(role.id), 'resource_type': 'MODULE', 'target': m, 'actions': ['VIEW'], 'expires_at': None, 'origin': '角色菜单'} for m in role.modules) for setting in UserMenuSetting.objects.all(): rows.extend({'id': f'user-menu:{setting.user_id}:{m}', 'subject_type': 'USER', 'subject_id': str(setting.user_id), 'resource_type': 'MODULE', 'target': m, 'actions': ['VIEW'], 'expires_at': None, 'origin': '原菜单授权'} for m in setting.menu_list or []) for g in WorkspaceUserResourcePermission.objects.filter(workspace_id='default'): # Owner/framework ROLE rows are not discretionary grants. if 'ROLE' in g.permission_list: continue actions = list(ACTIONS) if 'MANAGE' in g.permission_list else (['VIEW', 'USE'] if 'VIEW' in g.permission_list else []) rows.append({'id': f'legacy-resource:{g.id}', 'subject_type': 'USER', 'subject_id': str(g.user_id), 'resource_type': g.auth_target_type, 'target': g.target, 'actions': actions, 'expires_at': None, 'origin': '原资源授权'}) for kind in ('PARSER', 'SERVICE'): for obj in resource_models()[kind].objects.filter(workspace_id='default'): rows.extend({'id': f'legacy-share:{kind}:{obj.id}:{uid}', 'subject_type': 'USER', 'subject_id': uid, 'resource_type': kind, 'target': str(obj.id), 'actions': ['VIEW', 'USE'], 'expires_at': None, 'origin': '原资源授权'} for uid in obj.allowed_users) for role in PlatformRole.objects.exclude(id=ADMIN_ROLE_ID): if {'tool', 'mindmap'} & set(role.modules): rows.append({'id': f'inherited-feature:{role.id}', 'subject_type': 'ROLE', 'subject_id': str(role.id), 'resource_type': 'FEATURE', 'target': 'document_parse', 'actions': ['VIEW', 'USE'], 'expires_at': None, 'origin': '菜单附带', 'readonly': True}) for setting in UserMenuSetting.objects.all(): if {'tool', 'mindmap'} & set(setting.menu_list or []): rows.append({'id': f'inherited-user-feature:{setting.user_id}', 'subject_type': 'USER', 'subject_id': str(setting.user_id), 'resource_type': 'FEATURE', 'target': 'document_parse', 'actions': ['VIEW', 'USE'], 'expires_at': None, 'origin': '菜单附带', 'readonly': True}) return [row for row in rows if row['resource_type'] != 'FEATURE'] def remove_compatibility_grant(key, expected=None): from system_manage.models import UserMenuSetting, WorkspaceUserResourcePermission row = next((r for r in authorization_rows() if str(r['id']) == key and r.get('origin')), None) if row is None: raise ValidationError('授权已变更,请刷新') if row.get('readonly'): raise ValidationError('此权限随原菜单生效,请调整菜单授权') if expected and any(str(expected.get(k)) != str(row[k]) for k in ('subject_type', 'subject_id', 'resource_type', 'target')): raise ValidationError('授权对象不匹配') parts = key.split(':') if parts[0] == 'role-menu': role = PlatformRole.objects.select_for_update().get(pk=row['subject_id']) role.modules = [m for m in role.modules if m != row['target']] role.save(update_fields=['modules', 'updated_at']) elif parts[0] == 'user-menu': setting = UserMenuSetting.objects.select_for_update().get(user_id=row['subject_id']) setting.menu_list = [m for m in setting.menu_list if m != row['target']] setting.save(update_fields=['menu_list']) elif parts[0] == 'legacy-resource': WorkspaceUserResourcePermission.objects.filter(pk=parts[1]).delete() from users.serializers.user_manage_ext import invalidate_user_auth_cache transaction.on_commit(lambda: invalidate_user_auth_cache(row['subject_id'])) elif parts[0] == 'legacy-share': obj = resource_models()[row['resource_type']].objects.select_for_update().get(pk=row['target']) obj.allowed_users = [uid for uid in obj.allowed_users if uid != row['subject_id']] obj.save(update_fields=['allowed_users']) def parser_feature_actions(user): """Old tool/mindmap menus include parsing; new feature grants are explicit.""" if not user.is_active: return set() if is_admin(user): return {'VIEW', 'USE'} from system_manage.models import UserMenuSetting inherited = any({'tool', 'mindmap'} & set(role.modules) for role in roles_for(user)) setting = UserMenuSetting.objects.filter(user_id=user.id).first() inherited = inherited or bool(setting and {'tool', 'mindmap'} & set(setting.menu_list or [])) return ({'VIEW', 'USE'} if inherited else set()) | resource_actions(user, 'FEATURE', 'document_parse')