1、settings

"""
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

2、rbac应用下的models

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 = "菜单表"

models.py

3、urls

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),
]

urls.py

4、初始化   server--init_permission

#!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) #菜单相关
# 1、先去掉不是菜单的
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)

sever下的init_permission.py

5、app01下的views

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("编辑订单")

views.py

6、中间件

#!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

middlewear下的rbac.py

7、templatetags下的rbac.py

#!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}

自定义标签rbac.py

8、template

{% 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>

base.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>

index.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>

login.html

{% extends "base.html" %}
{% block content %}
<h1>订单页面</h1>
{% endblock %}

order.html

{% extends "base.html" %}
{% block content %}
{% if pagpermission.has_add %}
<a href="/userinfo/add/">添加</a>
{% endif %}
<table border="">
<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 %}

userinfo.html

{% 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 %}

userinfo_add.html

{% 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>#}

xxxx.html

9、static---rbac---rbac.css

.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;
}

rbac.css

10、static---rbac---rbac.js

// 方式一
$(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')
// }
// })
// });

rbac.js

Django框架----权限组件(具体代码实现)的更多相关文章

  1. Django框架----权限管理(设计分析以及具体细节)

    说起权限我们大家都知道,不一样的角色会有不一样的权限.比如就像学生管理系统一样,管理员,老师,学生之间的权限都是不一样的,那么展示的页面也是不一样的.所以,我们现在来看看具体操作. 目标:生成一个独立 ...

  2. 【django之权限组件】

    一.需求分析 RBAC(Role-Based Access Control,基于角色的访问控制),就是用户通过角色与权限进行关联.简单地说,一个用户拥有若干角色,一个角色拥有若干权限.这样,就构造成& ...

  3. Django 框架 Form组件

    一.Form组件简介 Form组件是django中一个非常强大的组件,在处理服务端和前端的交互上大大的提高了开发人员的开发速度. Form组件的功能: 用于处理前后端的数据认证(显示错误信息) 用于生 ...

  4. Django框架----Form组件

    Form介绍 我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来. 与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否 ...

  5. Django框架 --序列化组件(serializer)

    一 .Django自带序列化组件 Django内置的serializers(把对象序列化成json字符串) from django.core import serializers from djang ...

  6. Django框架----Form组件补充

    一.Form类 创建Form类时,主要涉及到 [字段] 和 [插件],字段用于对用户请求数据的验证,插件用于自动生成HTML; 1.Django内置字段如下: 1 Field 2 required=T ...

  7. Django万能权限框架组件

    业务场景分析 假设我们在开发一个培训机构的 客户关系管理系统,系统分客户管理.学员管理.教学管理3个大模块,每个模块大体功能如下 客户管理 销售人员可以录入客户信息,对客户进行跟踪,为客户办理报名手续 ...

  8. Django框架深入了解_03(DRF之认证组件、权限组件、频率组件、token)

    一.认证组件 使用方法: ①写一个认证类,新建文件:my_examine.py # 导入需要继承的基类BaseAuthentication from rest_framework.authentica ...

  9. Django框架之DRF 认证组件源码分析、权限组件源码分析、频率组件源码分析

    认证组件 权限组件 频率组件

随机推荐

  1. 011-ThreadFactory线程工厂

    一.源码分析 ThreadFactory是一个线程工厂.用来创建线程.这里为什么要使用线程工厂呢?其实就是为了统一在创建线程时设置一些参数,如是否守护线程.线程一些特性等,如优先级.通过这个Tread ...

  2. vue-自定义全局键盘码

    1.Vue.config.keyCodes.enter=13; //main.js中定义全局 <template> <div> <input v-model=" ...

  3. [js]promise学习2

    let fs = require("fs"), path = require('path'); 普通读取文件方法 /* fs.readFile(path.resolve('./da ...

  4. (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m

    在linux环境下配置项目运行环境时,部署的人员都会分配一下内存,以保证程序正常的运行.其实在开发的时候(window系统),就已经涉及到内存分配了,只是这些参数有默认值,因此一直没有去重视它. 以M ...

  5. Tensorflow实现LeNet-5、Saver保存与读取

    一. LeNet-5 LeNet-5是一种用于手写体字符识别的非常高效的卷积神经网络. 卷积神经网络能够很好的利用图像的结构信息. 卷积层的参数较少,这也是由卷积层的主要特性即局部连接和共享权重所决定 ...

  6. iOS UI基础-19.0 UICollectionView

    直接上代码,说明请看注释吧 1.继承三个代理 UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateF ...

  7. smali加入日志

    const-string v0, "aaatag"const-string v1, "msg"invoke-static {v0,v1}, Landroid/u ...

  8. Python实现selenium回放时间设置

    一般在做selenium时会有,回放快慢的需求. 实现思路: 1.一般写selenium会自定义findelement函数,来实现查找元素. 2.在查找函数上加个睡眠时间的装饰器,函数执行完等待若干秒 ...

  9. web前端 ajax请求报415/400错

    一.当使用jQuery 的ajax发送请求时 1.请求路劲没有出错并且不存在跨域,出现415错误 解决方法:在ajax请求中加上contentType: 'application/json', $.a ...

  10. unity之复制文本到剪贴板

    代码如下: static void CopyString(string str) { TextEditor te = new TextEditor(); te.text = str; te.Selec ...