一、settingscss
""" Django settings for day80 project. Generated by 'django-admin startproject' using Django 1.11.6. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7x(f$0j0c#)hn)8i(uv6j*sg^h_7v9$eak#pu_n4ji05=v28ca' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'rbac', ] from django.middleware.common import CommonMiddleware 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.middlewear.rbac.Middle', ] ROOT_URLCONF = 'day80.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'day80.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' # ==========靜態文件配置========= STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) # ==========rbac============ PERMISSION_URL_DICT = "permission_url_list" PERMISSION_MENU_KEY = "permission_menu_list" # =========白名單(不須要權限就能夠看到的)========== WHITE_LIST =[ "/login/", "/admin.*", "/index/", ] settings.py
二、rbac應用下的modelshtml
from django.db import models # Create your models here. class Role(models.Model): title = models.CharField(max_length=32,verbose_name="角色") permissions = models.ManyToManyField(to="Permission",verbose_name="擁有權限的角色",blank=True) #權限和角色是多對多的關係 def __str__(self): return self.title class Meta: verbose_name_plural = "角色表" class Permission(models.Model): title = models.CharField(max_length=32,verbose_name="權限名") url = models.CharField(max_length=32,verbose_name="帶正則的url") codes = models.CharField(max_length=32,verbose_name="代碼") group = models.ForeignKey(to="Group",verbose_name="所屬組",blank=True) #組和權限是一對多的關係,一個組有多個權限 menu_gp = models.ForeignKey(to='Permission',related_name='aaa',null=True,blank=True,verbose_name="組內菜單") def __str__(self): return self.title class Meta: verbose_name_plural = "權限表" class UserInfo(models.Model): name = models.CharField(max_length=32,verbose_name="姓名") password = models.CharField(max_length=64,verbose_name="密碼") email = models.CharField(max_length=32,verbose_name="郵箱") roles = models.ManyToManyField(to="Role",blank=True) #用戶和角色是多對多的關係 def __str__(self): return self.name class Meta: verbose_name_plural = "用戶表" class Group(models.Model): title = models.CharField(max_length=32,verbose_name="組名稱") menu = models.ForeignKey(to="Menu",verbose_name="組內菜單",blank=True) #一個組下有多個菜單 def __str__(self): return self.title class Meta: verbose_name_plural = "組" class Menu(models.Model): caption = models.CharField(max_length=32,verbose_name="菜單") def __str__(self): return self.caption class Meta: verbose_name_plural = "菜單表"
三、urlspython
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', views.login), url(r'^index/$', views.index), url(r'^userinfo/$', views.userinfo), url(r'^userinfo/add/$', views.userinfo_add), url(r'^userinfo/del/(\d+)/$', views.userinfo_del), url(r'^userinfo/edit/(\d+)/$', views.userinfo_edit), url(r'^order/$', views.order), url(r'^order/add/$', views.order_add), url(r'^order/del/(\d+)/$', views.order_del), url(r'^order/edit/(\d+)/$', views.order_edit), ]
四、初始化 server--init_permissionjquery
#!usr/bin/env python # -*- coding:utf-8 -*- from django.conf import settings def init_permission(user, request): ''' 初始化權限信息,獲取權限信息並放置到session中 :param user: :param request: :return: ''' permission_list = user.roles.values('permissions__id', 'permissions__title', # 用戶列表 'permissions__url', 'permissions__codes', 'permissions__menu_gp_id', # 組內菜單ID,Null表示是菜單 'permissions__group_id', 'permissions__group__menu_id', # 菜單ID 'permissions__group__menu__caption', # 菜單名稱 ).distinct() # 獲取當前角色對象的全部的權限並去重 # print(permission_list) # 權限相關 url_dict = {} for item in permission_list: group_id = item["permissions__group_id"] url = item["permissions__url"] code = item["permissions__codes"] # print("code_list", code) if group_id in url_dict: url_dict[group_id]["code"].append(code) # 若是id在裏面就把code和url添加進去 url_dict[group_id]["urls"].append(url) else: # 若是不在就設置 url_dict[group_id] = { "code": [code, ], "urls": [url, ] } request.session[settings.PERMISSION_URL_DICT] = url_dict print(url_dict) #菜單相關 # 一、先去掉不是菜單的 menu_list = [] for item in permission_list: tpl = { "id":item["permissions__id"], "title":item["permissions__title"], "url":item["permissions__url"], "menu_gp_id":item["permissions__menu_gp_id"], "menu_id":item["permissions__group__menu_id"], "menu_title":item["permissions__group__menu__caption"] } menu_list.append(tpl) request.session[settings.PERMISSION_MENU_KEY] = menu_list print("============",menu_list)
五、app01下的viewssql
from django.shortcuts import render, redirect, HttpResponse from django.conf import settings # Create your views here. from rbac import models import re from rbac.service.init_permission import init_permission class BasePagPermission(object): def __init__(self, code_list): self.code_list = code_list def has_add(self): if "add" in self.code_list: return True def has_del(self): if "del" in self.code_list: return True def has_edit(self): if "edit" in self.code_list: return True def login(request): if request.method == "GET": return render(request, "login.html") else: username = request.POST.get("username") password = request.POST.get("password") user = models.UserInfo.objects.filter(name=username, password=password).first() if user: init_permission(user, request) return redirect("/userinfo/") else: return render(request, "login.html") def index(request): return render(request, "index.html") def userinfo(request): pagpermission = BasePagPermission(request.permission_code_url) # 實例化 # print("code......", request.permission_code_url) data_list = [ {"id": 1, "name": "haiyan1"}, {"id": 2, "name": "haiyan2"}, {"id": 3, "name": "haiyan3"}, {"id": 4, "name": "haiyan4"}, {"id": 5, "name": "haiyan5"}, ] #print("data_list",data_list) #print("pagpermission",pagpermission) return render(request, "userinfo.html", {"data_list": data_list, "pagpermission": pagpermission}) def userinfo_add(request): if request.method == "GET": return render(request,"userinfo_add.html") else: return redirect("/userinfo/") def userinfo_del(request, nid): return HttpResponse("刪除用戶") def userinfo_edit(request, nid): return HttpResponse("編輯用戶") def order(request): pagpermission = BasePagPermission(request.permission_code_url) # 實例化 print("code......", request.permission_code_url) return render(request,"order.html",{"pagpermission":pagpermission}) def order_add(request): return HttpResponse("添加訂單") def order_del(request, nid): return HttpResponse("刪除訂單") def order_edit(request, nid): return HttpResponse("編輯訂單")
六、中間件數據庫
#!usr/bin/env python # -*- coding:utf-8 -*- from django.shortcuts import render, redirect, HttpResponse from django.conf import settings import re class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response class Middle(MiddlewareMixin): # 必須去繼承這個類 def process_request(self, request): current_url = request.path_info # 獲取當前請求的路徑 # 若是匹配的是白名單裏面的就讓經過,不須要權限 for url in settings.WHITE_LIST: if re.match(url, current_url): return None permission_dict = request.session.get(settings.PERMISSION_URL_DICT) # 獲取session if not permission_dict: # 若是沒有獲得,就直接跳轉到login頁面 return redirect("/login/") flag = False for group_id, code_url in permission_dict.items(): for db_url in code_url["urls"]: regex = "^{0}$".format(db_url) # 由於match匹配的時候會把你只要有的都匹配到了,咱們只匹配當前的url,因此得加一個起始終止符 # print(regex, current_url) if re.match(regex, current_url): # print(1111111) request.permission_code_url = code_url["code"] # 用戶輸入的url和數據庫的url匹配成功以後成功以後先把code保存在request中,方便之後判斷 flag = True break # 若是匹配成功就進入頁面 # 注意在這裏不能用return,在中間件中process_request這個函數若是有return就只會執行本身的 # response和上面的response,不會執行後續的。沒有return就會去繼續執行後續中間件和視圖函數 if flag: # 結束外層循環 break if not flag: return HttpResponse("無權訪問") # 若是訪問不成功就顯示無權訪問 def process_reponse(self, request, response): return response
七、templatetags下的rbac.pydjango
#!usr/bin/env python # -*- coding:utf-8 -*- from django.conf import settings import re from django.template import Library register = Library() @register.inclusion_tag("xxxx.html") def menu_html(request): """ 去Session中獲取菜單相關信息,匹配當前URL,生成菜單 :param request: :return: """ menu_list = request.session.get(settings.PERMISSION_MENU_KEY) current_url = request.path_info menu_dict = {} for item in menu_list: # 循環找到能夠做爲菜單的權限 if not item["menu_gp_id"]: menu_dict[item["id"]] = item # 正則匹配添加active for item in menu_list: regex = "^{0}$".format(item["url"]) if re.match(regex, current_url): # 匹配成功在根據id去判斷,若是菜單id有值就不是菜單,則去找它的值對應的id,添加active # ,爲null時就是菜單,直接給本身添加一個active if not item["menu_gp_id"]: #是菜單 menu_dict[item["id"]]["active"] = True else: menu_dict[item["menu_gp_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': active, 'children': [ {'title': item['title'], 'url': item['url'], 'active': active} ] } print("result",result) return {"menu_dict":result}
八、templatec#
{% load rbac %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> <link rel="stylesheet" href="/static/rbac/rbac.css"> </head> <body> <div class="aaa"> <div class="left"> {% menu_html request %} </div> <div class="right"> {% block content %} {% endblock %} </div> </div> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/rbac/rbac.js"></script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> </head> <body> <h1>hello--{{ user.name }}</h1> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> </head> <body> <form method="post" action="/login/"> {% csrf_token %} <p>姓名:<input type="text" name="username"></p> <p>密碼:<input type="password" name="password"></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
{% extends "base.html" %} {% block content %} <h1>訂單頁面</h1> {% endblock %}
{% extends "base.html" %} {% block content %} {% if pagpermission.has_add %} <a href="/userinfo/add/">添加</a> {% endif %} <table border="1"> <thead> <th>編號</th> <th>姓名</th> <th>操做</th> </thead> <tbody> {% for row in data_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.name }}</td> <td> {% if pagpermission.has_edit %} <a href="#">編輯</a> {% endif %} {% if pagpermission.has_del %} <a href="#">刪除</a> {% endif %} </td> </tr> {% endfor %} </tbody> </table> {% endblock %}
{% extends "base.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} <p>編號:<input type="text" name="bianhao"></p> <p>姓名:<input type="text" name="name"></p> <input type="submit" value="提交"> </form> {% endblock %}
{% for k,item in menu_dict.items %} <div class="item-title">{{ item.menu_title }}</div> {% if item.active %} <div class="item-permission"> {% else %} <div class="item-permission hide"> {% endif %} {% for v in item.children %} {% if v.active %} <a href="{{ v.url }}" class="active">{{ v.title }}</a> {% else %} <a href="{{ v.url }}">{{ v.title }}</a> {% endif %} {% endfor %} </div> {% endfor %} {# <div class="item-title">菜單一</div>#} {# <div class="item-permission">#} {# <a href="">用戶列表</a>#} {# <a href="">訂單列表</a>#} {# </div>#} {# <div class="item-title">菜單二</div>#} {# <div class="item-permission hide">#} {# <a href="">用戶列表</a>#} {# <a href="">訂單列表</a>#} {# </div>#}
九、static---rbac---rbac.csssession
.left{ float: left; width: 20%; height: 500px; background-color: coral; padding: 20px 20px; } .right{ width: 80%; height: 500px; background-color: azure; } .item-permission a{ display: block; } .hide{ display: none; } .item-permission a.active{ color: red; }
十、static---rbac---rbac.jsapp
// 方式一 $(function () { $(".item-title").click(function () { $(this).next().toggleClass("hide") }) }); // 方式二: // $(function () { // $('.item-title').click(function () { // if($(this).next().hasClass('hide')){ // $(this).next().removeClass('hide') // }else{ // $(this).next().addClass('hide') // } // }) // });