如何设置特定模型实例的添加,删除,更新和查看权限?

时间:2011-04-19 21:55:52

标签: python django permissions django-admin authorization

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

我在我的FooAdmin课程中覆盖了has_add_permissionhas_delete_permission,但似乎没有任何效果。

要求:

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

    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,但想不出任何东西。

1 个答案:

答案 0 :(得分:1)

经过一段谷歌搜索和随机黑客攻击后,我能够找到解决方案。我不知道协议的回答是什么。

  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}