Rights Management of Django Web Framework II

Source: Internet
Author: User

1. Login Log In

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. User.objects.filter (Username=username,password=password). First ()        if User:            init_permission (user,request)            return redirect ('/index/')        else:            return redirect ('/login/')

2. Init_permission (user,request) Custom session

From django.conf import settingsdef init_permission (user,request):
  # fetch Data Permission_list = user.roles.values (' permission__id ', ' permission__title ', ' Permission__u RL ', ' permission__code ', ' permission__menu_group ', ' permission__group_id ', ' Permission__group_ _caption ', ' permission__group__menu_id ', ' permission__group__menu__title ',). Distinct () Current_url = Request.path_info # Filter Permissions related to result = {} # User-owned action code and accessible URL address--permissions related to item in PERMISSION_LIST:GROUP_ id=item[' permission__group_id '] code = item[' Permission__code '] url=item[' permission__url '] if Group_ ID in result:result[group_id][' codes '].append (code) result[group_id][' URLs '].append (URL) Els e:result[group_id]={' codes ': [Code,], ' URLs ': [URL,],} # Session added Dictionary request.session[settings. Permission_url_dict_key] = result # filter menu Related menu_list = [] for item in permission_list:msg = { ' ID ': item[' permission__id '], ' title ': item[' permission__title ', ' url ': item[' Permission__u RL '], ' menu_gp_id ': item[' permission__menu_group ', ' menu_id ': item[' permission__group__menu_id '],  ' Menu_title ': item[' Permission__group__menu__title ',} menu_list.append (msg) # session added Dictionary Request.session[settings. Permission_menu_key]=menu_list

3. Setting Configuration

permission_url_dict_key= ' permission_url_dict '   # permission URL data permission_menu_key= ' permission_menu_dict '      # Menu Dictionary Data

4. Creating middleware

Path: E:\permission80\rbac\middleware\rbac.py

Import refrom django.conf import settingsfrom django.shortcuts import Redirect,render,httpresponseclass 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 response# inherits the parent class Middlewaremixin method class Rbacmiddleware (middlewaremixin): def process_request (self,request): Current_url=request.path_info # takes the path information of the user method: for example/index/,/userinfo/# Determines whether the path that the user accesses is in the whitelist for the URL in settings. Valid_url:regax= "^{0}$". Format (URL)
# If the match succeeds in stopping the match, none continues to execute the other middleware, if none is directly matched to the URL routing rule (/index/, views.index) if Re.match (Regax,current_url): Return None # takes the permission data from the session, the path Permission_dict=request.session.get under User permissions (settings. Permission_url_dict_key)
# if not, jump to the login path if not Permission_dict:return redirect ('/login/') Flag=false for group_id, Code_url_dic in Permission_dict.items (): For Db_url in code_url_dic[' URLs ']: regax= "^{0}$". Forma T (Db_url)
# The path that matches the current user right is which path if Re.match (Regax,current_url):
# Add a dictionary to the request with values corresponding to the codes code for the user's access: For example, add list edit request.permission_code_list=code_url_dic[ ' Codes '] flag=true break if flag:break if not flag : Return HttpResponse (' Unauthorized access ')

5. Setting Configuration Middleware

# white list valid_url=[    '/login/',    '/logoff/',    '/index/',    '/test/',    '/admin.* ',]# Join the middleware list 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.middleware.rbac.RbacMiddleware ',]

6. Custom templates

Path: E:\permission80\rbac\templatetags\rbactag.py

A. First create the template directory Templatetags, the name must be the same

Import refrom django.conf import settingsfrom django.template Import libraryregister = Library () # Reference HTML file tag.html@ Register.inclusion_tag (' tag.html ') def menu_html (Request): # takes the menu data from the custom session via request Permission_menu = Request.ses Sion[settings. Permission_menu_key] Current_url = Request.path_info menu_dict = {} for item in Permission_menu: # Determine if the group menu is         In Menu_dict, if not item[' menu_gp_id ': menu_dict[item[' menu_id ']] = Item for item in Permission_menu:  Regax = "^{0}$". Format (item[' URL ')) # matches the path that the user accesses is the menu_dict, adds a Actvie activity to the path to the access if Re.match (Regax,                Current_url): menu_gp_id = item[' menu_id '] if menu_gp_id: # menu Group Add active menu_dict[menu_gp_id][' active '] = True else: # In-group menu list add menu_dict[item[' id ']][' Active '] = True result = {} for item in Menu_dict.values (): active = item.get (' active ') menu_id = Item      [' menu_id ']  If menu_id in result:result[menu_id][' Children '].append ({' title ': item[' title '], ' url ': item[' url '), ' active ': active}) if active:result[menu_id][' active '] = True else:result[menu_id] = {' menu_id ': item[' menu_id ', ' menu_title ': item[' menu_title '], ' active ': a                ctive, ' children ': [{' title ': item[' title '], ' url ': item[' url '], ' active ': active}     ]} return {' menu_dict ': result}

  

  

  

 

  

Rights Management of Django Web Framework II

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.