Django - user permission, user role, user guide

  • Preface (refer to the teacher's notes)
    RBAC (Role-Based Access Control) refers to the association between users and permissions through roles. Simply put, a user has several roles, and each role has several permissions. In this way, the authorization model of "user role permission" is constructed. In this model, the relationship between users and roles and between roles and permissions is generally many to many.

Simple permission: the following is a simple permission design pattern, which includes user table, role table and permission table.
Picture png
A slightly more complex permission may be designed into user table, permission table, role table, user group table and additional permission table. The permission related models of these columns are provided in django. The association relationship of tables in permission design is as follows:
Picture png


    1. Permission item of Django
      Django uses the permission object to store permission items. Each model has three permissions by default, namely add model, change model and delete model. For example, define a model called student student. When the table is migrated, it will be displayed in auth_ Three corresponding permissions are automatically created in Permission: add_student, change_student and delete_student. Django also allows you to customize permissions.

Picture png
** 2. Create permissions**
1) Custom permissions

Add the permissions parameter to the Meta element of the user-defined model. The name of the user-defined permission ('codename ',' name ') means codename is the permission name and name is the description of the permission. Auth in database_ There is another permission in the content table_ Type field, which indicates which model the permission belongs to

from django.db import models

class Users(AbstractUser):
    administrators---expand User surface
    class Meta:
        permissions = (
            ('add_user_per', 'Add user permissions'),
            ('del_user_per', 'Delete user permissions'),
            ('change_user_per', 'Modify user permissions'),
            ('sel_user_per', 'Query user permissions')

And in settings Add the following settings to the PY file:

AUTH_USER_MODEL = 'users.Users'

Note: in the auth of the database_ Permissions will be added in the permission table, including the built-in permissions for Users management and four user-defined permissions.

As follows:

[image upload failed... (image-ee6095-1537444192584)]

2) Create permissions

The above method is to customize permissions when defining the model, which can also be understood as creating built-in permissions of the system. If it involves creating permissions in business logic, you can create permissions through the Permission model

url(r'^add_user_permission/', views.add_user_permission,name='add_user_permission'),

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse

from users.models import Users

def add_user_permission(request):
    if request.method == 'GET':
        # Gets the id value of the current Users model
        content_type = ContentType.objects.get_for_model(Users)
        # codename refers to the permission name, name refers to the description and content_type is the ID of which model the current permission belongs to
                                  name='Add additional user permissions',
        return HttpResponse('Permission created successfully')
  • 3. Assign permissions
    1) Add certain permissions directly to users

The method of directly assigning permissions is adopted to add additional permissions to Users, including user table Users, Permission model and intermediate table user_ The association between permissions. There is a ManyToManyField() many to many association relationship between the user Users model and Permission. The association field is user_permission.


Add permission: user object user_permission.add(permission object 1, permission object 2)

Delete permission: user object user_permission.remove(permission object 1, permission object 2)

Clear permissions: user object user_permission.clear()

 url(r'^add_permission/', views.add_permission, name='add_permission'),

 from django.contrib.auth.models import Permission, User

 def add_permission(request):
     if request.method == 'GET':
         # Get user object with id=1d
         user = Users.objects.get(id=1)
         # Add permissions to this user
         pers = Permission.objects.filter(codename__in=['add_user_per', 'del_user_per'])
         for per in pers:
             # Add user permissions
             #Delete permissions
             # user.user_permissions.remove(per)
         # Clear permissions
         return HttpResponse('Permission created successfully')

2) Create a group and assign permissions to the corresponding group

Adding permissions to a group involves the group table, permission permission table, and intermediate association table. It is ManyToManyFiled() Association, and the association field is permissions syntax:

Add permission: group object permissions.add(permission object 1, permission object 2)

Delete permission: group object permissions.remove(permission object 1, permission object 2)

Clear permission: group object permissions.clear()

url(r'^group_permission/', views.group_permission, name='group_permission'),

def group_permission(request):
    if request.method == 'GET':
        # Create a super management user group and give the user group permission to CRUD users
        super_group = Group.objects.create(name='Super administrator')
        pers = Permission.objects.filter(codename__in=['add_user_per', 'del_user_per', 'change_user_per', 'sel_user_per'])
        for per in pers:
            # Add permissions for superuser group
            # Permission to delete a supergroup
        # Clear group permissions
        return HttpResponse('Create group permissions')

3) Assign users and permission groups

Adding group permissions to users involves group tables, user user tables, and intermediate association tables. It is ManyToManyFiled() association relationship, and the association field is groups syntax:

Add permission: user object groups.add(groups object 1, groups object 2)

Delete permission: user object groups.remove(groups object 1, groups object 2)

Clear permissions: user object groups.clear()

url(r'^user_group/', views.user_group, name='user_group'),

def user_group(request):
    if request.method == 'GET':
        # Assign the super administrator group permission to the user with id 1
        # Get super administrator group object
        super_group = Group.objects.get(name='Super administrator')
        # Get user object with id=1d
        user = Users.objects.get(id=1)
        # Add permissions for superuser group
        # Permission to delete a supergroup
        # user.groups.remove(super_group)
        # Clear group permissions
        # user.groups.clear()
        return HttpResponse('Create user group permissions')
    1. Check whether the user has certain permissions, all permissions and group permissions
      Syntax: user object has_perm('model name. Permission codename ')

Query all user permissions: user get_ all_ The permissions () method lists all permissions of the user, and the return value is permission name

Query user's group permission: user get_ group_ The permissions () method lists the permissions of the group to which the user belongs, and the return value is permission name

def user_permission(request):
    if request.method == 'GET':
        # Get user object with id=1d
        user = Users.objects.get(id=1)
        # View all user permissions
        all_perm = user.get_all_permissions()
        # View user's group permissions
        group_perm = user.get_group_permissions()
        # Query whether the user has an add_user_per permissions
        if user.has_perm('users.add_user_per'):
            return HttpResponse('Users have add_user_per jurisdiction')
            return HttpResponse('No user add_user_per jurisdiction')
    1. Permission verification, using permission_required decorator
      Use permission_required to verify the permission. If the user who does not currently log in to the system does not have the permission, jump to the login page. If the current user has the permission, access the corresponding view function.

Syntax: @ permission_required('app name. Permission name codename ')

url(r'^add_user_html/', views.add_user_html, name='add_user_html'),

from django.contrib.auth.decorators import permission_required

def add_user_html(request):
    if request.method == 'GET':
        return HttpResponse('This method needs to add user permissions to access')
    1. test
      Define the login route and realize the login operation. After the user logs in, access add again_ user_ HTML routing address, you can access the corresponding view function. If the user does not log in, you cannot access add because of permission problems_ user_ View function corresponding to HTML route.
    1. Home page index Through permission control buttons in HTML
      Use in template: the template uses the global variable perms to store all permissions of the current user. All permissions can be printed through {{perms. Application name}}.

In the template, you can also directly obtain the user information of the currently logged in system through {{user}}.

Use syntax format:

{% if perms.Application name.Permission ID %}
    <!-- Here is the content displayed only with permission -->
{% endif %}

home page index.html Permissions of the following control buttons in:

{% extends 'base.html' %}

{% block title %}
    home page
{% endblock %}

{% block content %}

    <!--Use global variables in templates perms Store all permissions of the current user-->
    {{ perms.users }}
    <!--Judge whether the current user is a super administrator-->
    {{ user.is_superuser }}

    {% if user.is_superuser or perms.users.add_user_per %}
        <p>Add user management</p>
    {% endif %}
    {% if user.is_superuser or perms.users.del_user_per %}
        <p>Delete user management</p>
    {% endif %}
    {% if user.is_superuser or perms.users.change_user_per %}
        <p>Modify user management</p>
    {% endif %}
    {% if user.is_superuser or perms.users.sel_user_per %}
        <p>Query user management</p>
    {% endif %}
{% endblock %}

Tags: Back-end Python Django

Posted by razorsedgeuk on Fri, 15 Apr 2022 07:47:03 +0930