Skip to main content
 首页 » 编程设计

python之如何为特定模型实例设置添加、删除、更新和查看权限

2025年05月04日13bhlsheji

我是 Python 和 Django 的新手,正在开发 Django 应用程序,我有一个要求,我必须在我的 Django 中管理模型实例 Foo 的权限。还有其他模型实例可用,但权限仅适用于 foo。

我已经在我的 FooAdmin 类中覆盖了 has_add_permission、has_delete_permission,但似乎没有任何效果。

要求:

  1. 添加Foo对象:用户必须是 super 管理员
  2. 删除Foo对象:用户必须是 super 管理员
  3. 编辑现有的 Foo 对象:用户必须属于 ldap 组“foo-edit”。如果用户属于这个组,那么他/她只能编辑一个字段(建筑物)(尚未实现)
  4. 查看 Foo:如果用户属于 ldap 组“foo-access”,则该用户只有查看权限。 (待调查)
  5. 如果要添加、更新、删除或修改任何其他模型实例,则规则 1 到 4 不适用。

我的实现:

class FooAdmin(ModelAdmin): 
  ... 
  ... 
  ... 
  def has_add_permission(self, request): 
    permissions = self.opts.app_label + '.' + self.opts.get_add_permission() 
    # Other objects are fine. 
    user = request.user 
    if (user.has_perm('survey.add_foo') and user.is_authenticated 
        and user.is_superuser): 
      return True 
    return False 
 
  def has_delete_permission(self, request, obj=None): 
    permissions = self.opts.app_label + '.' + self.opts.get_delete_permission() 
    user = request.user 
    if (user.has_perm('survey.delete_foo') and user.is_authenticated 
        and user.is_superuser): 
      return True 
    return False 

问题:

  1. 我可以创建另一个 Bar 类型的实例,但不能删除我刚刚创建的实例。这不是 FooBar 类型实例的问题。 BarAdmin 实现没有任何代码来管理权限,就像 FooBarAdmin 实现一样。

    有没有办法解决这个问题并使 Bar 和 FooBar 再次可删除?

  2. 如何实现要求的#3 和 4?我可以覆盖 has_change_permission 方法来确定此人是否具有更改权限。如何仅授予用户对一个字段的编辑权限。

    Django 似乎不支持仅查看权限。我可以创建 has_view_permission(self, request) 和 get_model_perms(self, request) 等地方?但是我不确定如何实现它。我一直在寻找 Django source code但想不出任何东西。

请您参考如下方法:

经过一些谷歌搜索和随机黑客攻击后,我想出了一个解决方案。我不知道回答您问题的协议(protocol)是什么。

  1. 创建一个中间件实现 (threadlocals.py),将用户信息存储在线程本地对象中。

    try: 
      from threading import local 
    except ImportError: 
      from django.utils._threading_local import local 
     
    _thread_locals = local() 
    def get_current_user(): 
      return getattr(_thread_locals, 'user', None) 
     
    class ThreadLocals(object): 
      """Middleware that gets various objects from the request object and 
      saves them in thread local storage.""" 
     
      def process_request(self, request): 
        _thread_locals.user = getattr(request, 'user', None) 
    
  2. 创建一个将检查权限的授权实用程序模块。

    import ldap   
    from django.contrib.auth.models import User     
    from myapp.middleware import threadlocals 
     
    def can_edit(): 
      user_obj = threadlocals.get_current_user() 
      if user_obj and (is_superadmin(user_obj.username) or \ 
          is_part_of_group(user_obj.username, 'foo-edit')): 
        return True 
      return False 
     
    def can_edit_selectively(): 
      user = threadlocals.get_current_user() 
      if (user and not user.is_superuser and 
          is_part_of_group(user.username, 'foo-edit')): 
        return True 
      return False 
     
    def can_view_only(): 
      user_obj = threadlocals.get_current_user() 
      if (user_obj and not user_obj.is_superuser and 
          is_part_of_group(user_obj.username, 'foo-access') and 
          not is_part_of_group(user_obj.username, 'foo-edit')): 
        return True 
      return False 
     
    def has_add_foo_permission(): 
      user = threadlocals.get_current_user() 
      if (user and user.has_perm('survey.add_foo') and user.is_authenticated 
          and user.is_superuser): 
        return True 
      return False 
     
    def has_delete_foo_permission(): 
      user = threadlocals.get_current_user() 
      if (user and user.has_perm('survey.delete_foo') and user.is_authenticated 
          and user.is_superuser): 
        return True 
      return False 
     
    def is_superadmin(logged_in_user): 
       admin = False 
       try: 
         user = User.objects.get(username=logged_in_user) 
         if user.is_superuser: 
           admin = True 
         except User.DoesNotExist: 
           pass 
      return admin 
     
    def is_part_of_group(user, group): 
      try: 
        user_obj = User.objects.get(username=user) 
        if user_obj.groups.filter(name=group): 
          return True 
      except User.DoesNotExist: 
        pass 
      conn = ldap.open("ldap.corp.mycompany.com") 
      conn.simple_bind_s('', '') 
      base = "ou=Groups,dc=mycompany,dc=com" 
      scope = ldap.SCOPE_SUBTREE 
      filterstr = "cn=%s" % group 
      retrieve_attributes = None 
      try: 
        ldap_result_id = conn.search_s(base, scope, filterstr, retrieve_attributes) 
        if ldap_result_id: 
          results = ldap_result_id[0][1] 
          return user in results['memberUid'] 
      except ldap.LDAPError: 
        pass 
      return False 
    
  3. 设置管理员。在操作中,评估权限。此外,如果用户没有删除权限,则“删除 Foo”操作不可用。

    class FooAdmin(ModelAdmin): 
     
      ... 
     
      def get_actions(self, request): 
        actions = super(FooAdmin, self).get_actions(request) 
        delete_permission = self.has_delete_permission(request) 
        if actions and not delete_permission: 
          del actions['delete_selected'] 
        return actions 
     
      def has_add_permission(self, request): 
        return auth_utils.has_add_foo_permission() 
     
      def has_delete_permission(self, request, obj=None): 
        return auth_utils.has_delete_foo_permission() 
     
      .... 
    
  4. 修改ModelForm实现中的init函数

     class FooForm(ModelForm): 
     
       def __init__(self, *args, **kwargs): 
         self.can_view_only = (auth_utils.can_view_only() and 
                               not auth_utils.can_edit_selectively()) 
         self.can_edit_selectively = (auth_utils.can_edit_selectively() or 
                                      auth_utils.can_view_only()) 
         if self.can_edit_selectively: 
           ... Set the widget attributes to read only. 
     
         # If the user has view only rights, then disable edit rights for building id. 
         if self.can_view_only: 
           self.fields['buildingid'].widget = forms.widgets.TextInput() 
           self.fields['buildingid'].widget.attrs['readonly'] = True 
         elif (auth_utils.can_edit() or auth_utils.can_edit_selectively()): 
           self.fields['buildingid'].widget=forms.Select(choices= 
                                                    utils.get_table_values('building')) 
    
  5. 我还必须禁用修改提交行的操作。

    def submit_edit_selected_row(context): 
      opts = context['opts'] 
      change = context['change'] 
      is_popup = context['is_popup'] 
      save_as = context['save_as'] 
      if opts.object_name.lower() != 'foo': 
        has_delete = (not is_popup and context['has_delete_permission'] 
                      and (change or context['show_delete'])) 
        has_save_as_new = not is_popup and change and save_as 
        has_save_and_add_another = (context['has_add_permission'] and 
                                    not is_popup and (not save_as or context['add'])) 
        has_save_and_continue = (context['has_add_permission'] and 
                                 not is_popup and (not save_as or context['add'])) 
        has_save = True 
      else: 
        has_delete = auth_utils.has_delete_pop_permission() 
        has_save_as_new = auth_utils.has_add_pop_permission() 
        has_save_and_add_another = auth_utils.has_add_pop_permission() 
        has_save_and_continue = (auth_utils.can_edit() or 
                                 auth_utils.can_edit_selectively()) 
        has_save = auth_utils.can_edit() or auth_utils.can_edit_selectively() 
      return { 
        'onclick_attrib': (opts.get_ordered_objects() and change 
                              and 'onclick="submitOrderForm();"' or ''), 
        'show_delete_link': has_delete, 
        'show_save_as_as_new': has_save_as_new, 
        'show_save_and_add_another': has_save_and_add_another, 
        'show_save_and_continue': has_save_and_continue, 
        'is_popup': is_popup, 
        'show_save': has_save 
       } 
    register.inclusion_tag('admin/submit_line.html', takes_context=True) (submit_edit_selected_row) 
    
  6. 我不得不修改扩展管理模板。其余保持不变。

    {% if save_on_top %} {% submit_edit_selected_row %} {% endif}