django--Permissions Component (middleware to determine user rights--url)

Source: Internet
Author: User

Permissions

Restrict the resources a user can access based on a URL

The relationship between project and application

Projects can contain multiple applications
Apps can be included in multiple projects
RBAC: A privilege-based management system

Project

Create a Django project first

Model

 fromDjango.dbImportModelsclassUserInfo (models. Model): Name= Models. Charfield (max_length=32) PWD= Models. Charfield (max_length=32,default=123) Email=models. Emailfield () Roles= Models. Manytomanyfield (to="Role")    def __str__(self):returnSelf.nameclassRole (models. Model): Title=models. Charfield (max_length=32) Permissions= Models. Manytomanyfield (to="Permission")    def __str__(self):returnSelf.titleclassPermission (models. Model): URL= Models. Charfield (max_length=32) Title= Models. Charfield (max_length=32)    def __str__(self):returnSelf.title

Front-end templates

<!DOCTYPE HTML><HTMLLang= "ZH-CN"><Head>    <MetaCharSet= "UTF-8">    <Metahttp-equiv= "X-ua-compatible"content= "Ie=edge">    <Metaname= "Viewport"content= "Width=device-width, initial-scale=1">    <title>Title</title></Head><Body><formAction= "/login/"Method= "POST">{% Csrf_token%}<P>User name<inputtype= "text"name= "User"></P>    <P>Password<inputtype= "Password"name= "pwd"></P>    <P><inputtype= "Submit"value= "Login"></P></form></Body></HTML>

Url

Urlpatterns = [    url (r'^admin/', admin.site.urls),    URL (r')  ^login/', views.login),    URL (r'^users/' ) , views.user_list),    URL (r'^orders/', views.role_list),] 

Back end

 fromDjango.shortcutsImportRender, HttpResponse, redirect fromRbac.modelsImportUserInfo, Role, PermissiondefLogin (Request):ifRequest.method = ="GET":        returnRender (Request,"login.html")    ifRequest.method = ="POST": Username= Request. Post.get ("User") PWD= Request. Post.get ("pwd") User= UserInfo.objects.filter (Name=username, pwd=pwd). First ()ifuser:request.session["user_id"] =user.pk permission_list= User.roles.all (). VALUES ("Permissions__url","Permissions__title"). DISTINCT () temp= []             forPer_urlinchPermission_list:temp.append (per_url["Permissions__url"]) request.session["permissions_list"] =TempPrint(temp)returnHttpResponse ("OK")        Else:            returnredirect'/login/')defuser_list (Request):returnHttpResponse ("User List")defrole_list (Request):returnHttpResponse ("Order List")

The backend has a lot of view functions, if you write the adorner to determine whether the user has access, there are 30 view functions, you need to add the adorner function on 30 view functions, so the method of the adorner is not appropriate, instead of the middleware method

 fromDjango.utils.deprecationImportMiddlewaremixin#Note fromDjango.shortcutsImportRender,redirect, HttpResponse fromRbac.modelsImportUserInfoImportRe#NoteclassM1 (middlewaremixin):defprocess_request (self,request): Current_path=Request.path_info permission_list= Request.session.get ("permissions_list")        Print(permission_list) Valid_menu= ["/login/","/reg/","/admin/.*"]#If you do not set the whitelist, the admin URL will also be sentenced to no permissions, and do not need to verify the number of functions, the first set of white list,                                        #If the user enters a URL that will return to None in the whitelist         forValid_urlinchValid_menu:ret= Re.match (Valid_url,current_path)#Note            ifret:returnNoneif  notpermission_list:returnNone flage=False forPer_urlinchPermission_list:re_macth=Re.match (Per_url,current_path)ifRe_macth:flage=True Break        if  notFlage:returnHttpResponse ("No Permissions")
To create an intermediate price

1, create an application in the project application, the name of itself as to why? This is mentioned earlier: "An app can be included in multiple projects" for easy use later

2. Create a folder service in the project,

3. Create a PY file in the service

4. Create a class that must inherit Middlewaremixin

5, there must be a function in this class, process_request

Do the above steps, the effect is as

django--Permissions Component (middleware to determine user rights--url)

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.