Django permission mechanism implementation code details, django permission mechanism details

Source: Internet
Author: User

Django permission mechanism implementation code details, django permission mechanism details

This article focuses on the Django permission mechanism.

1. Django permission mechanism Overview

The permission mechanism can constrain user behavior, control the display content of the page, and make the API more secure and flexible. Using the permission mechanism can make the system more powerful and robust. Therefore, it is necessary to clarify the Django permission mechanism for Django-based development.

1.1 Django permission Control

Django uses user, group, and permission to complete the permission mechanism. This permission mechanism grants a certain permission of the model to the user or group and can be understood as a global permission, that is, if user A has the write permission on model B, user A can modify all the instances (objects) of model B ). The same is true for group permissions. If group C is granted the write permission of model B, All Users affiliated with group C can modify all instances of model B.

This permission mechanism can only meet some simple application requirements. In most application scenarios, more detailed permission mechanisms are required. Taking the blog system as an example, users of the blog system can be divided into four user groups: "Administrator", "edit", "author", and "Reader; the blog system administrator and editor have the permission to view, modify, and delete all articles. The author can only modify and delete the articles he/she has written, while the reader has only the permission to read the articles. For administrator, edit, and reader permissions, we can use global permissions for control. For authors, global permissions cannot meet the requirements, but only through global permissions, either allow the author to edit an article that is not his own, or make the author unable to modify his own article.

In the preceding application scenario, the permission mechanism provided by Django cannot meet the requirements, and another finer permission mechanism should be introduced: object permission (object permission ).

Object Permission is a Permission mechanism for Object granularity. It allows authorization for each specific Object. The original example is still used. If model B has three instances B1, B2, and B3, and if we grant the write permission of B1 to user A, A can modify the B1 object, b2 and B3 cannot be modified.

The same applies to group C. If you grant the write permission of B2 to group C, all users belonging to group C can modify B2, but B1 and B3 cannot be modified. In combination with Django's built-in permission mechanism and object permission, the author's permission control in the blog system can be easily solved: The system does not allow the author to edit articles globally, but gives the edit permission to the specific articles belonging to the author.

Django actually contains the object permission framework, but there is no specific implementation. The implementation of object permission requires the use of a third-party app django-guardian. We can call the methods encapsulated by django guradian during development.

1.2 Django permission items

Django uses the permission object to store permission items. Each model has three permission by default, that is, add model, change model, and delete model. For example, if you define a model named "Car" and define a Car, three permission: add_car, change_car, and delete_car are automatically created. Django also allows customization of permission. For example, we can create new permission items for Car: drive_car, clean_car, fix_car, etc.

It should be noted that permission always corresponds to the model. If an object is not a model instance, we cannot create or assign permissions to it.

2. Applications with built-in Permission mechanism of Django 2.1 Permission

As described above, After Django defines each model, the add, change, and delete permission of the model will be added by default. The custom permission can be manually added when we define the model:

class Task(models.Model):  ...  class Meta:    permissions = (      ("view_task", "Can see available tasks"),      ("change_task_status", "Can change the status of tasks"),      ("close_task", "Can remove a task by setting its status as closed"),    )

Each permission isdjango.contrib.auth.PermissionType instance. The type contains three fields: name, codename, and content_type. content_type reflects the model of the permission, and codename is used for checking the permission in the Code logic, name is the description of permission. When you print a permission to a screen or page, name is displayed by default.

Create custom permissions in the model. From the perspective of system development, you can understand the built-in permissions for creating a system. If you need to create custom permissions when using the system, use the following method:

from myapp.models import BlogPostfrom django.contrib.auth.models import Permissionfrom django.contrib.contenttypes.models import ContentTypecontent_type = ContentType.objects.get_for_model(BlogPost)permission = Permission.objects.create(codename='can_publish',                    name='Can Publish Posts',                    content_type=content_type)
2.2 User Permission management

The user_permission field of the User object manages the User's permissions:

Myuser. user_permissions = [permission_list] myuser. user_permissions.add (permission, permission ,...) # Add the permission myuser. user_permissions.remove (permission, permission ,...) # Delete permission myuser. user_permissions.clear () # Clear permissions ##################################### ######################### note: the above permission is django. contrib. auth. permission instances #################################### ##########################

Use the has_perm () method to check user permissions:

myuser.has_perm('myapp.fix_car')

has_perm()The method parameter, that is, the codename of permission. However, when passing the parameter, you must add the prefix of the app to which the model belongs. The format is<app label>.<permission codename>.

Whether permission is granted to a user or a group,has_perm()Applicable methods

Note:
The user. get_all_permissions () method lists all permissions of a user. The returned value is the list of permission names.
The user. get_group_permissions () method lists the permissions of the group to which the user belongs. The returned value is the list of permission names.

2.3 Group Permission management

The group permission management logic is consistent with the user permission management. The permissions field is used in the group for permission management:

group.permissions = [permission_list]group.permissions.add(permission, permission, ...)group.permissions.remove(permission, permission, ...)group.permissions.clear()

Permission check:

Still useduser.has_perm()Method.

2.4 permission_required

Permissions can constrain user behavior. When permission checks are involved in the business logic, decorator can separate permission verification and core business logic to make the code simpler and clearer. The decorator of permission ispermission_required:

from django.contrib.auth.decorators import permission_required@permission_required('car.drive_car')def my_view(request):
2.5 check permissions in Template

The global variable perms is used in the Template to store all permissions of the current user. For permission check, refer to the following example:

{% if perms.main.add_page %}      <li class="dropdown">       <a href="#" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Pages <span class="caret"></span></a>       <ul class="dropdown-menu" role="menu">        <li><a href="{% url 'main:admin_pages' %}" rel="external nofollow" >All Pages</a></li>        <li><a href="{% url 'main:admin_page' %}" rel="external nofollow" >New Page</a></li>        <li><a href="{% url 'main:admin_pages' %}?draft=true" rel="external nofollow" >Drafts</a></li>       </ul>      </li>{% endif %}
3. Application of object permission based on Django-guardian

Django-guardian extends django's permission Mechanism Based on django's native logic. After applying django-guardian, you can use the methods provided by django-guardian and native django methods to check global permissions, the object permission mechanism provided by django-guardian improves django's permission mechanism.

For more information about django-guardian, see the official documentation. The common methods for object permission are as follows:

from guardian.shortcuts import assign_perm, get_permsfrom guardian.core import ObjectPermissionCheckerfrom guardian.decorators import permission_required
3.1 add object permission

Add object permissionassign_perm()Method, such as adding drive_car permissions to the mycar object to the user:

assign_perm('myapp.drive_car', request.user, mycar)

The assign_perm () method can also be used for group

assign_perm('myapp.drive_car', mygroup, mycar)
3.2 permission check

3.2.1 Global permission

The get_perms () method is used to check the user's global permission, which is the same as user. has_perm (), for example:

############################## It works! ############################# if not 'main.change_post' in get_perms(request.user, post):   raise HttpResponse('Forbidden')############################## It works, too!#############################if not request.user.has_perm('main.change_post')  return HttpResponse('Forbidden')

In this example, although the post object is passed as a parameterget_perms()Method, but it only checks whether the user's global permissions have the main. change_post permission. In many cases, the nativeuser.has_permBut both user and group can be usedget_perms()In some cases, the code can be more concise.

3.2.2 Object permission

Use in Django-guardianObjectPermissionCheckerCheck the user's object permission, for example:

checker = ObjectPermissionChecker(request.user)print checker.has_perm('main.change_post', post)

3.3 permission_required

guardian.decorators.permission_requiredIs the decorator of django-guardian permission check. It can check both global permissions and object permissions,accept_global_permsThe parameter indicates whether to check the global permission of the user, for example:

from guardian.decorators import permission_requiredclass DeletePost(View):  @method_decorator(permission_required('main.delete_post',               (models.Post, 'id', 'pk'),               accept_global_perms=True))  def get(self, request, pk):    try:      pk = int(pk)      cur_post = models.Post.objects.get(pk=pk)      is_draft = cur_post.is_draft      url = reverse('main:admin_posts')      if is_draft:        url = '{0}?draft=true'.format(url)        cur_post.delete()    except models.Post.DoesNotExist:      raise Http404    return redirect(url)

Note:
(Models. post, 'id', 'pk') is used to specify the object instance. If this parameter is ignored, the global permission is only checked whether the value of accept_global_perms is True or False.

4. Conclusion

Django native provides a simple global permission control mechanism, but object permission is more useful in many application scenarios; django-guardian is currently an active django extension. It provides an effective object permission control mechanism, which is consistent with django's native mechanism and is recommended for use.

The above is all the details about the Django permission mechanism implementation code, and I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.