前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django权限管理(Permission)

django权限管理(Permission)

作者头像
程序员同行者
发布2018-07-02 16:56:06
6.6K1
发布2018-07-02 16:56:06
举报
文章被收录于专栏:程序员同行者
什么是权限管理
  • 权限管理,一般指根据系统设置的安全规则或者安全策略,用户可以访问而且只能访问自 己被授权的资源
  • 权限管理好比如钥匙,有了钥匙就能把门打开,但是权限设置是有级别之分的,假如这个 系统有多个权限级别就如一间屋有多个门,想要把所有门都打开您必须要取得所有的钥 匙,就如系统一样。
django权限机制
  • django权限机制能够约束用户行为,控制页面的显示内容,也能使API更加安全和灵活;用好权限机制,能让系统更加强大和健壮
django权限控制
  • Django用user,group和permission完成了权限机制,这个权限机制是将属于model的某个permission赋予user或group,可以理解为全局的权限,即如果用户A对数据模型(model)B有可写权限,那么A能修改model B的所有实例(objects)。group的权限也是如此,如果为group C 赋予model B的可写权限,则隶属于group C的所有用户,都可以修改model B的所有 实例。
Django的权限项
  • Django用permission对象存储权限项,每个model默认都有三个permission,即add model, change model和delete model permission总是与model对应的,如果一个object不是model的实例,我们无法为它创建 /分配权限
默认权限
  • 在 INSTALLED_APPS 设置中列出django.contrib.auth 后,安装的各个应用中的每个 Django 模 型默认都有三个权限:添加、修改和删除。每次运行 manage.py migrate 命令创建新模型时都 会为其赋予这三个权限。
分组
  • django.contrib.auth.models.Group 模型是为用户分类的通用方式,这样便可以为一批用户 赋予权限或添加其 他标注。用户所属的分组数量不限。一个分组中的用户自动获得赋予那 个分组的权限。
  • 除了权限之外,分组还是为用户分类的便捷方式,分组后可以给用户添加标签,或者扩展功能
权限应用
  • Permission
  • User Permission
  • Group Permission
  • 权限检查
Permission
  • Django定义每个model后,默认都会添加该model的add, change和delete三个 permission,自定义的permission可以在我们定义model时手动添加
代码语言:javascript
复制
class Server(models.Model):
...
class Meta:
    permissions = (
    ("view_server", "can view server"),
    ("change_server_status", "Can change the status of server"),
    )
    #codename == view_server权限验证项
    #name == can view server 可读的名称
  • 每个permission都是django.contrib.auth.Permission类型的实例,该类型包含三个字段 name, codename 和 content_type

content_type反应了permission属于哪个model, codename 如上面的view_server,代码逻辑中检查权限时要用, name是permission的描述,将permission打印到屏幕或页面时默认显示的就是name

User Permission
  • User对象的user_permission字段管理用户的权限
代码语言:javascript
复制
user = User.objects.get(username="rock")
user.user_permissions = [permission_list]
user.user_permissions.add(permission, permission, …) #增加权限
user.user_permissions.remove(permission, permission, …) #删除权限
user.user_permissions.clear() #清空权限
user.get_all_permissions() #列出用户的所有权限
user.get_group_permissions() # 列出用户所属group的权限
  • 练习
代码语言:javascript
复制
In [1]: from django.contrib.auth.models import  Group,User,Permission
In [3]: user  = User.objects.get(username='rock-1')
In [4]: user.groups.all
Out[4]: <bound method BaseManager.all of <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fd86cf49ef0>>
In [5]: user.groups.all()
Out[5]: <QuerySet [<Group: 51reboot>]>

In [6]: user.user_permissions.all()
Out[6]: <QuerySet []>
In [7]: per = Permission.objects.get(id=21)
In [8]: per.codename
Out[8]: 'delete_idc'

In [9]: user.user_permissions.add(per)

In [10]: user.user_permissions.all()
Out[10]: <QuerySet [<Permission: resources | idc | Can delete idc>]>

In [11]: user.user_permissions.remove(per)

In [12]: user.user_permissions.all()
Out[12]: <QuerySet []>

In [13]: user.user_permissions.add(per)

In [14]: user.user_permissions.clear()

In [15]: user.user_permissions.add(per)

In [16]: user.get_all_permissions()
Out[16]: 
{'admin.add_logentry',
 'admin.change_logentry',
 'admin.delete_logentry',
 'auth.add_group',
 'auth.add_permission',
 'auth.add_user',
 'auth.change_group',
 'auth.change_permission',
 'auth.change_user',
 'auth.delete_group',
 'auth.delete_permission',
 'auth.delete_user',
 'contenttypes.add_contenttype',
 'contenttypes.change_contenttype',
 'contenttypes.delete_contenttype',
 'resources.add_idc',
 'resources.change_idc',
 'resources.delete_idc',
 'sessions.add_session',
 'sessions.change_session',
 'sessions.delete_session'}

In [17]: user.groups.clear()

In [18]: user.get_all_permissions()
Out[18]: 
{'admin.add_logentry',
 'admin.change_logentry',
 'admin.delete_logentry',
 'auth.add_group',
 'auth.add_permission',
 'auth.add_user',
 'auth.change_group',
 'auth.change_permission',
 'auth.change_user',
 'auth.delete_group',
 'auth.delete_permission',
 'auth.delete_user',
 'contenttypes.add_contenttype',
 'contenttypes.change_contenttype',
 'contenttypes.delete_contenttype',
 'resources.add_idc',
 'resources.change_idc',
 'resources.delete_idc',
 'sessions.add_session',
 'sessions.change_session',
 'sessions.delete_session'}

In [19]: user.get_group_permissions()
Out[19]: 
{'admin.add_logentry',
 'admin.change_logentry',
 'admin.delete_logentry',
 'auth.add_group',
 'auth.add_permission',
 'auth.add_user',
 'auth.change_group',
 'auth.change_permission',
 'auth.change_user',
 'auth.delete_group',
 'auth.delete_permission',
 'auth.delete_user',
 'contenttypes.add_contenttype',
 'contenttypes.change_contenttype',
 'contenttypes.delete_contenttype',
 'resources.add_idc',
 'resources.change_idc',
 'resources.delete_idc',
 'sessions.add_session',
 'sessions.change_session',
 'sessions.delete_session'}

In [20]: user.groups.all()
Out[20]: <QuerySet []>
Group Permission
  • group permission管理逻辑与user permission管理一致,group中使用permissions字段做 权限管理
代码语言:javascript
复制
group.permissions.set([permission_list])#设置权限
group.permissions.add(permission, permission, …)#添加权限
group.permissions.remove(permission, permission, …)#删除权限
group.permissions.clear()#情况权限
  • 练习
代码语言:javascript
复制
In [40]: group = Group.objects.get(name='51reboot')#取出一个组
In [41]: group.permissions.all()#列出组所有权限
Out[41]: <QuerySet [<Permission: admin | log entry | Can add log entry>, <Permission: admin | log entry | Can change log entry>, <Permission: admin | log entry | Can delete log entry>, <Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | permission | Can add permission>, <Permission: auth | permission | Can change permission>, <Permission: auth | permission | Can delete permission>, <Permission: auth | user | Can add user>, <Permission: auth | user | Can change user>, <Permission: auth | user | Can delete user>, <Permission: contenttypes | content type | Can add content type>, <Permission: contenttypes | content type | Can change content type>, <Permission: contenttypes | content type | Can delete content type>, <Permission: resources | idc | Can add idc>, <Permission: resources | idc | Can change idc>, <Permission: resources | idc | Can delete idc>, <Permission: sessions | session | Can add session>, <Permission: sessions | session | Can change session>, '...(remaining elements truncated)...']>

In [42]: permission = Permission.objects.get(id=20)#先取出一个权限(Can change idc)

In [43]: group.permissions.remove(permission)#从组里删除这个权限

In [44]: group.permissions.all()#再次查看权限
Out[44]: <QuerySet [<Permission: admin | log entry | Can add log entry>, <Permission: admin | log entry | Can change log entry>, <Permission: admin | log entry | Can delete log entry>, <Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | permission | Can add permission>, <Permission: auth | permission | Can change permission>, <Permission: auth | permission | Can delete permission>, <Permission: auth | user | Can add user>, <Permission: auth | user | Can change user>, <Permission: auth | user | Can delete user>, <Permission: contenttypes | content type | Can add content type>, <Permission: contenttypes | content type | Can change content type>, <Permission: contenttypes | content type | Can delete content type>, <Permission: resources | idc | Can add idc>, <Permission: resources | idc | Can delete idc>, <Permission: sessions | session | Can add session>, <Permission: sessions | session | Can change session>, <Permission: sessions | session | Can delete session>]>

In [45]: group.permissions.add(permission)添加权限

In [46]: group.permissions.all()#再次查看权限
Out[46]: <QuerySet [<Permission: admin | log entry | Can add log entry>, <Permission: admin | log entry | Can change log entry>, <Permission: admin | log entry | Can delete log entry>, <Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | permission | Can add permission>, <Permission: auth | permission | Can change permission>, <Permission: auth | permission | Can delete permission>, <Permission: auth | user | Can add user>, <Permission: auth | user | Can change user>, <Permission: auth | user | Can delete user>, <Permission: contenttypes | content type | Can add content type>, <Permission: contenttypes | content type | Can change content type>, <Permission: contenttypes | content type | Can delete content type>, <Permission: resources | idc | Can add idc>, <Permission: resources | idc | Can change idc>, <Permission: resources | idc | Can delete idc>, <Permission: sessions | session | Can add session>, <Permission: sessions | session | Can change session>, '...(remaining elements truncated)...']>

In [48]: group.permissions.set([permission])#设置权限,会清空之前的所有权限,传入一个权限列表

In [49]: group.permissions.all()#再次查看权限
Out[49]: <QuerySet [<Permission: resources | idc | Can change idc>]>

In [50]: group.permissions.clear()#清空所有权限

In [51]: group.permissions.all()#再次查看权限
Out[51]: <QuerySet []>
权限验证-普通视图
  • 在视图中验证权限—— permission_required,
  • 当业务逻辑中涉及到权限检查时,decorator能够分离权限验证和核心的业务逻辑,使代码更 简洁,逻辑更清晰。permission的decorator为permission_required
代码语言:javascript
复制
from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required(’dashboard.view_server')
def my_view(request,*args,**kwargs):
权限验证-类视图
代码语言:javascript
复制
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required, permission_required
class ServerView(TemplateView):
    @method_decorator(login_required)
    @method_decorator(permission_required(“dashboard.view_server”)
    def get(self, request, *args, **kwargs):
    ...
权限验证-view代码中验证
代码语言:javascript
复制
if not request.user.has_perm(’dashboard.view_server')
    return HttpResponse('Forbidden')
权限验证-模板中验证
  • 验证是否有登陆
代码语言:javascript
复制
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
  • 验证是否有权限
代码语言:javascript
复制
{% if perms.dashboard.view_server %}
有权限
{% endif %}
PermissionRequiredMixin
代码语言:javascript
复制
from django.contrib.auth.mixins import PermissionRequiredMixin
class IndexView(LoginRequiredMixin,PermissionRequiredMixin,TemplateView):
    template_name = 'index.html'
自定义PermissionRequiredMixin
创建仅限
  • 在模型的 Meta 类中定制权限
代码语言:javascript
复制
class Meta:
    permissions = (
    ("modify_user_status", "修改用户状态"),
    ("modify_user_passwd", "修改用户密码"),
    )
  • 直接创建权限
代码语言:javascript
复制
from resources.models import Idc
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(Idc)
permission = Permission.objects.create(codename='can_view',
name='Can view Idc',
content_type=content_type)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是权限管理
  • django权限机制
  • django权限控制
  • Django的权限项
  • 默认权限
  • 分组
  • 权限应用
    • Permission
      • User Permission
        • Group Permission
          • 权限验证-普通视图
            • 权限验证-类视图
              • 权限验证-view代码中验证
                • 权限验证-模板中验证
                  • PermissionRequiredMixin
                    • 自定义PermissionRequiredMixin
                      • 创建仅限
                      相关产品与服务
                      对象存储
                      对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档