Rights Management of the Django web framework

Source: Internet
Author: User

1. Demand Analysis:

Preparation: Create a standalone APP,RBAC #权限管理模块/component App01 #应用

Assign permissions, URL

2. Database design

2.1 Design Ideas

First edition: Permission table: ID          URL                        title                     is_menu 1         /index/                     home                        False                2         /userinfo/                  user list                    True 3         /userinfo/add/              Add user                    True 4         /userinfo/del/(\d+)/        Delete user                    False 5         /userinfo/edit/ (\d+)/       Modify user                    False  user table: ID          username        password ...    . 1           panyu             123 2           crevice             123 3           Jelly             123 4           luning             123 Rights user Relationship table: User ID         permission ID    1             1   1             2   1             3   1             4   1             5   2             1   2             2   2             3   3             1   4             1   4             2   4             3

  

  

Second Edition: User table: ID          username        password ...    . 1           panyu             123 2           crevice             123 3           Jelly             123 4           luning             123  role table: ID          title  1            CEO 2            CTO 4            COO 5            Department manager 6            Technician user and Role Relationship table: User ID       role ID  1            1  1            2  1            4  2  5 3            6  4            6 Permissions table: ID          URL                        Title 1         /index/                     home 2         /userinfo/                  user List 3         / userinfo/add/              Add user 4         /userinfo/del/(\d+)/        Delete User 5         /userinfo/edit/(\d+)/        Modify User Role Permissions Relationship table: Role ID           Permission ID   1                1

2.2 Creating a Table class app01.models.py

From django.db import Modelsclass UserInfo (models. Model): Username=models. Charfield (max_length=32,verbose_name= ' username ') password=models. Charfield (max_length=32,verbose_name= ' password ') email=models. Charfield (max_length=32,verbose_name= ' mail ') roles=models. Manytomanyfield (to= ' role ', verbose_name= ' all roles ', Blank=true) class meta:verbose_name_plural= ' User table ' Def __str_ _ (Self): return Self.usernameclass Permissions (models. Model): Title=models. Charfield (max_length=64,verbose_name= ' title ') url=models. Charfield (max_length=64,verbose_name= ' with regular URL ') Is_menu =models. Booleanfield (verbose_name= ' is Menu ') class meta:verbose_name_plural= ' permission table ' Def __str__ (self): return sel F.titleclass Role (models. Model): Title=models. Charfield (max_length=32) permissions=models.  Manytomanyfield (to= ' Permissions ', Verbose_name= ' has all permissions ', Blank=true) class meta:verbose_name_plural= ' role table ' Def __str__ (self): return Self.title

  

3. Permission Entry:

CEO: Panyu/userinfo//userinfo/add//userinfo/edit/(\d+)//userinfo/del/(\d+)//order//order/add//order/edit/(\d+)// order/del/(\d+)/Director: Luning/userinfo//userinfo/add//order//order/add/Manager: Kidney Pine/userinfo//order/Clerk: Kidney pine, Wen Fei, Salar/order/ps: Go back to the problem: 1. User Login-Get all the roles that the current user has-get all the permissions the current user has-get all the permissions that the current user has (de-weight)

  

4. Permission Grooming

A. Creating an RBAC app B. Creating a table structure, RBAC, role-based permissions control-three classes-five tables C. Input permission data based on Django admin Python manage.py createsuperuser-root-root!2345d. User logon Program-gets all permissions (de-rabc.service.init_permissiondef) that the current user has-gets the URL in the permission, and puts it into session init_permission (User,request): Passe. Middleware-whitelist-GET request Url-session saved permission information-loop Url,re.match (Db_url, Current_url)

  



5. The code in RBAC:

-models.py-admin.py-service.init_permission.py     #权限攻击组件-middlewares.rabc.py #中间件配置文件中setting配置白名单:
Valid_url = ["/login/", "/admin.*"]

6 Code Show

6.1 E:\Django Project Exercise 03\rbac\service\init_permissions.py

def init_permissions (user,request):    url_list = []    # gets all the URL permissions in user    permission_url_list = User.roles.values (' Permissions__url ', ' permissions__title ', ' permissions__is_menu '). Distinct ()    # Add URL permissions to the Url_list list for item in    permission_url_list:        url_list.append (item[' Permissions__url ')    Print (' url_list: ', url_list)    # Custom session    request.session[' permission_url_list '] = url_list

6.2 Middleware Setting Configuration

middleware = [    ' Django.middleware.security.SecurityMiddleware ',    ' Django.contrib.sessions.middleware.SessionMiddleware ', '    django.middleware.common.CommonMiddleware ',    ' Django.middleware.csrf.CsrfViewMiddleware ',    ' Django.contrib.auth.middleware.AuthenticationMiddleware ', '    django.contrib.messages.middleware.MessageMiddleware ',    ' Django.middleware.clickjacking.XFrameOptionsMiddleware ',    ' Rbac.middlewares.rbac.RbacMiddleware '     # Rights Management Component Reference Path]

6.3 rbac.py File Code E:\Django project Exercise 03\rbac\middlewares\rbac.py

Import refrom django.shortcuts import render,redirect,httpresponsefrom django.conf import Settingsclass Middlewaremixin (object): Def __init__ (self, get_response=none): Self.get_response = Get_response Super (Mi Ddlewaremixin, self). __init__ () def __call__ (self, request): Response = None if hasattr (self, ' process_re Quest '): Response = self.process_request (Request) if not response:response = Self.get_respon        SE (Request) if hasattr (self, ' process_response '): Response = Self.process_response (Request, response) Return Responseclass Rbacmiddleware (middlewaremixin): def process_request (self,request): # 1. Get the current request Url:req Uest.path_info # 2. Get permissions to save the current user in session # request.session.get ("permission_url_list") Current_url = R Equest.path_info # The current request does not need to perform a permission validation for the URL in settings. Valid_url:if Re.match (Url,current_url): Return None permission_list = Request.session.get ("Permission_url_list") print (' Permission_list ', permission_list) if not Permissio N_list:return Redirect ('/login/') Flag=false for Db_url in permission_list:regax= "^{ 0}$ ". Format (Db_url) if Re.match (regax,current_url): Flag =true Break If no T Flag:return HttpResponse (' Unauthorized access ')

6.4 Applying the path using the RBAC component: E:\Django Project Practice 03\app01\views.py

From django.shortcuts import render,redirect,httpresponsefrom app01 import Modelsfrom rbac.service.init_permissions Import init_permissions def login (Request):    if request.method== "GET":        return render (Request, ' login.html ')    else:        username=request. Post.get (' user ')        password=request. Post.get (' pwd ')        user=models. UserInfo.objects.filter (Username=username,password=password). First ()        if not User:            return render (Request, ' Login.html ')        else:            init_permissions (user,request) #定制session模块            return redirect ('/index/') def index ( Request):    return HttpResponse (' home page ') def userinfo (request):    return HttpResponse (' User Management ') def userinfo_add ( Request):    return HttpResponse (' Add user ') def order (Request):    return HttpResponse (' Order Management ') def order_add ( Request):    return HttpResponse (' Add order ')

6.5 Routing file configuration

From django.conf.urls import urlfrom django.contrib import adminfrom app01 import views as  App01_viewsurlpatterns = [ C1/>url (R ' ^admin/', admin.site.urls),    url (r ' ^login/', app01_views.login),    url (r ' ^index/', app01_ views.index),    url (r ' ^userinfo/$ ', app01_views.userinfo),    url (r ' ^userinfo/add/$ ', app01_views.userinfo_ Add),    URL (r ' ^order/$ ', app01_views.order),    url (r ' ^order/add/$ ', App01_views.order_add),]

  

 

Rights Management of the Django web framework

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.