一. login中注册 权限url

def login(request):
if request.method == "POST": username = request.POST.get("username")
pwd = request.POST.get("password")
user = models.User.objects.filter(name=username, pwd=pwd).first()
# print(user,"mmmmmmmmmmmmmmmmmmmmm") # riven
if user:
# 在session中注册用户id############################################
request.session["user_id"] = user.pk
# 在session注册权限列表
# 查询当前登录用户的所有权限
# < QuerySet[{'title': 'CEO', 'permissions__url': '"/users/"'}
# 调用函数登录封装设置url路径的session函数
initial_session(user, request)
"""
valures 查询原理
values:
temp=[]
for role in user.roles.all(): # [<Role: 保洁>,<Role: 销售>]
temp.append({
"title": role.title,
"permissions__url":role.permissions.all(), })
"""
return redirect("/users/")
return render(request, "login.html", locals())
# 调用函数登录封装设置url路径的session函数
# 调用函数登录封装设置url路径的session函数
def initial_session(user, request):
""" :param user: 当前登录用户
:param request: 就是request呀
:return: 返回
"""
permission = user.roles.all().values("permissions__url").distinct() # distinct() 去重的意思
permission_list = [] # 循环queryset取值
for item in permission:
permission_list.append(item["permissions__url"]) # ['"/users/"', '"/users/add/"', '"/roles/"'] # 将用户权限 注册到session当中####################################
request.session["permission_list"] = permission_list

二 . 在中间件中校验权限

import re
from django.shortcuts import render, redirect, HttpResponse
# 使用中间键来做权限校验
from django.utils.deprecation import MiddlewareMixin
class ValidPermission(MiddlewareMixin): def process_request(self, request):
# 当前访问路径
cerrent_path = request.path_info # /users/add/ # 因为下面操作限制了 login 的进去 尴尬一批所以定义了白名单
valid_url_list = ["/login/", "/reg/", "/admin/.*"]
for valid_url in valid_url_list:
valid_url = "^%s$" % valid_url # ^/users/$
ret = re.match(valid_url, cerrent_path)
if ret:
return None # 校验是否登录
user_id = request.session.get("user_id")
if not user_id:
return redirect("/login/") # 校验权限
# ['/users/', '/users/add/', '/roles/', '/users/delete/(\\d+)/', '/users/edit/(\\d+)/']
permission_list = request.session.get("permission_list", []) # 取值 取不到就返回一个空列表 flag = False
for permission in permission_list:
permission = "^%s$" % permission # ^/users/$
ret = re.match(permission, cerrent_path)
if ret:
flag = True
break if not flag:
return HttpResponse("没有访问权限") return None

参考代码:

from
from django.contrib import admin
from django.urls import path,re_path
from app01 import views urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^users/$', views.users),
re_path(r'^roles/$', views.roles),
re_path(r'^login/$', views.login),
re_path(r'^add_users/$', views.add_users),
re_path(r'^delete_users/(\d+)/$', views.delete_users),
re_path(r'^edeit_users/(\d+)/$', views.edeit_users),
re_path(r'^add_roles/$', views.add_roles),
re_path(r'^delete_roles/(\d+)/$', views.delete_roles),
re_path(r'^edeit_roles/(\d+)/$', views.edeit_roles),
]
 django.db import models

# Create your models here.

# 用户表
class User(models.Model):
name = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
roles = models.ManyToManyField(to="Role") def __str__(self):
return self.name # 角色表
class Role(models.Model):
title = models.CharField(max_length=32)
permissions=models.ManyToManyField(to="Permission") def __str__(self):
return self.title # 权限表
class Permission(models.Model):
title = models.CharField(max_length=32)
url = models.CharField(max_length=32) def __str__(self):
return self.title

from django.contrib import admin
from django.urls import path,re_path
from app01 import views urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^users/$', views.users),
re_path(r'^roles/$', views.roles),
re_path(r'^login/$', views.login),
re_path(r'^add_users/$', views.add_users),
re_path(r'^delete_users/(\d+)/$', views.delete_users),
re_path(r'^edeit_users/(\d+)/$', views.edeit_users),
re_path(r'^add_roles/$', views.add_roles),
re_path(r'^delete_roles/(\d+)/$', views.delete_roles),
re_path(r'^edeit_roles/(\d+)/$', views.edeit_roles),
]

# 调用函数登录封装设置url路径的session函数
def initial_session(user, request):
""" :param user: 当前登录用户
:param request: 就是request呀
:return: 返回
"""
permission = user.roles.all().values("permissions__url").distinct() # distinct() 去重的意思
permission_list = [] # 循环queryset取值
for item in permission:
permission_list.append(item["permissions__url"]) # ['"/users/"', '"/users/add/"', '"/roles/"'] # 将用户权限 注册到session当中####################################
request.session["permission_list"] = permission_list

import re
from django.shortcuts import render, redirect, HttpResponse
# 使用中间键来做权限校验
from django.utils.deprecation import MiddlewareMixin
class ValidPermission(MiddlewareMixin): def process_request(self, request):
# 当前访问路径
cerrent_path = request.path_info # /users/add/ # 因为下面操作限制了 login 的进去 尴尬一批所以定义了白名单
valid_url_list = ["/login/", "/reg/", "/admin/.*"]
for valid_url in valid_url_list:
valid_url = "^%s$" % valid_url # ^/users/$
ret = re.match(valid_url, cerrent_path)
if ret:
return None # 校验是否登录
user_id = request.session.get("user_id")
if not user_id:
return redirect("/login/") # 校验权限
# ['/users/', '/users/add/', '/roles/', '/users/delete/(\\d+)/', '/users/edit/(\\d+)/']
permission_list = request.session.get("permission_list", []) # 取值 取不到就返回一个空列表 flag = False
for permission in permission_list:
permission = "^%s$" % permission # ^/users/$
ret = re.match(permission, cerrent_path)
if ret:
flag = True
break if not flag:
return HttpResponse("没有访问权限") return None

from django.shortcuts import render, redirect, HttpResponse
from django.contrib import auth
# Create your views here.
from app01 import models
import re
from rbac_config.service.perssions import * def login(request):
if request.method == "POST": username = request.POST.get("username")
pwd = request.POST.get("password")
# 利用auth模块做用户名和密码的校验
user = models.User.objects.filter(name=username, pwd=pwd).first()
# print(user,"mmmmmmmmmmmmmmmmmmmmm") # riven
if user:
# 在session中注册用户id############################################
request.session["user_id"] = user.pk
# 在session注册权限列表
# 查询当前登录用户的所有权限
# < QuerySet[{'title': 'CEO', 'permissions__url': '"/users/"'}
# 调用函数登录封装设置url路径的session函数
initial_session(user, request)
"""
valures 查询原理
values:
temp=[]
for role in user.roles.all(): # [<Role: 保洁>,<Role: 销售>]
temp.append({
"title": role.title,
"permissions__url":role.permissions.all(), })
"""
return redirect("/users/")
return render(request, "login.html", locals()) def users(request):
user_list = models.User.objects.all()
active1 = 'active'
permission = request.session.get("permission_list", []) ret = False for i in permission:
if ('/delete_roles/(\\d+)/') == i:
ret = True if ('/edeit_roles/(\\d+)/') == i:
ret = True return render(request, "user.html", locals()) def add_users(request):
if request.method == "POST":
user_id = request.POST.getlist("add_user")
text_users = request.POST.get("text_users")
text_pwd = request.POST.get("text_pwd")
new_id = models.User.objects.create(name=text_users, pwd=text_pwd)
new_id.roles.add(*user_id) # 多对多字段添加方法
return redirect("/users/")
add_obj = models.Role.objects.all()
return render(request, "add_users.html", locals()) def delete_users(request, id):
models.User.objects.filter(id=id).delete()
return redirect("/users/") def edeit_users(request, id):
if request.method == "POST":
user_id = request.POST.getlist("add_user")
text_users = request.POST.get("text_users")
text_pwd = request.POST.get("text_pwd")
update_obj = models.User.objects.get(id=id)
update_obj.name = text_users
update_obj.pwd = text_pwd
# 多对多用set
update_obj.roles.set(user_id)
update_obj.save()
return redirect("/users/") user_text = models.User.objects.filter(id=id)
roles_list = user_text.values_list("roles__id")
roles_list_new = []
for i in roles_list:
roles_list_new.append(i[0])
role_list = models.Role.objects.all()
id = id
return render(request, "edeit_users.html", locals()) def roles(request):
roles_list = models.Role.objects.all()
active2 = 'active'
permission_roles = request.session.get("permission_list", []) ret = False for i in permission_roles:
if ('/delete_roles/(\\d+)/') == i:
ret = True if ('/edeit_roles/(\\d+)/') == i:
ret = True return render(request, "roles.html", locals()) def add_roles(request):
if request.method == "POST":
print(request.POST)
text_roles = request.POST.get("text_roles")
add_permission = request.POST.getlist("add_permission")
roles_obj = models.Role.objects.create(title=text_roles)
roles_obj.permissions.add(*add_permission)
return redirect("/roles/")
permission_obj = models.Permission.objects.all()
return render(request, "add_roles.html", locals()) def delete_roles(request, id):
models.Role.objects.filter(id=id).delete()
return redirect("/roles/") def edeit_roles(request, id):
if request.method == "POST":
text_roles = request.POST.get("text_roles")
add_permission = request.POST.getlist("add_permission")
new_roles = models.Role.objects.get(id=id)
new_roles.title = text_roles
new_roles.permissions.set(add_permission) # set时不需要打散
new_roles.save()
return redirect("/roles/") role_obj = models.Role.objects.all()
permission = models.Permission.objects.all()
role_obj_title = role_obj.filter(id=id)
permission_list = []
roles_obj_id = models.Role.objects.filter(id=id).values_list("permissions")
for ret in roles_obj_id:
permission_list.append(ret[0])
id = id
return render(request, "edeit_roles.html", locals())

{% extends "base.html" %}

{% block con %}
<form action="/add_roles/" method="post">
{% csrf_token %}
<div>
<p>角色<input type="text" name="text_roles"></p>
</div> <div>
<select name="add_permission" multiple>
{% for url in permission_obj %}
<option value="{{ url.id }}">{{ url }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">提交</button> </form> {% endblock %}

{% extends "base.html" %}

{% block con %}
<form action="/add_users/" method="post">
{% csrf_token %}
<p>用户名<input type="text" name="text_users"></p>
<p>密码<input type="password" name="text_pwd"></p>
<div>
<select name="add_user" multiple>
{% for add_user in add_obj %}
<option value="{{ add_user.id }}">{{ add_user }}</option>
{% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">提交</button> </form>
{% endblock %}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--配置手机端适应-->
<meta name="viewport" content="width=device-width,initial-scale=1">
<!--配置css文件 核心CSS样式压缩文件-->
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.css">
<!--配置jQuery-->
<script src="/static/bootstrap/jQuery.js"></script>
<!--配置 核心Boot script JS压缩文件-->
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<style>
.header {
width: 100%;
height: 60px;
background-color: #336699;
} .menu {
background-color: bisque;
position: fixed;
top: 60px;
bottom: 0px;
left: 0px;
width: 200px;
} .content {
position: fixed;
top: 60px;
bottom: 0;
right: 0;
left: 200px;
padding: 30px;
}
</style>
</head>
<body> <div class="header"></div>
<div class="container">
<div class="row">
<div class="menu col-md-3">
{% if "/users/" in permission or permission_roles %}
<a href="/users/" class="list-group-item {{ active1 }}">User_List</a>
{% endif %}
{% if "/roles/" in permission or permission_roles %}
<a href="/roles/" class="list-group-item {{ active2 }}">Roles_list</a>
{% endif %}
<div class="content col-md-8">
{% block con %}
{% endblock %}
</div> </div>
</div> </body>
</html>

{% extends "base.html" %}

{% block con %}
<form action="/edeit_roles/{{ id }}/" method="post">
{% csrf_token %}
<div>
<p>角色<input type="text" name="text_roles" value="{{ role_obj_title.0 }}"></p>
</div> <div>
<select name="add_permission" multiple>
{% for url in permission %}
{% if url.id in permission_list %}
<option selected value="{{ url.id }}">{{ url }}</option>
{% else %}
<option value="{{ url.id }}">{{ url }}</option>
{% endif %} {% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
{% endblock %}

{% extends "base.html" %}

{% block con %}

    <form action="/edeit_users/{{ id }}/" method="post">
{% csrf_token %}
<p>用户名<input type="text" name="text_users" value="{{ user_text.0 }}"></p>
<p>密码<input type="password" name="text_pwd"></p>
<div>
<select name="add_user" multiple >
{% for add_user in role_list %}
{% if add_user.id in roles_list_new %}
<option selected value="{{ add_user.id }}">{{ add_user }}</option>
{% else %}
<option value="{{ add_user.id }}">{{ add_user }}</option>
{% endif %} {% endfor %}
</select>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
{% endblock %}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--配置手机端适应-->
<meta name="viewport" content="width=device-width,initial-scale=1">
<!--配置css文件 核心CSS样式压缩文件-->
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.css">
<style>
.tou{
margin-top: 100px; } </style>
</head> <body> <div class="container tou">
<div class="row">
<form class="form-horizontal col-md-6 col-md-offset-3 login-form" action="/login/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="用户名">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="密码">
</div>
</div> <div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success" id="login-button">登录</button>
<span class="login-error"></span>
</div>
</div>
</form>
</div>
</div> <!--配置jQuery-->
<script src="/static/bootstrap/jQuery.js"></script>
<!--配置 核心Boot script JS压缩文件-->
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

{% extends "base.html" %}

{% block con %}
<h1>角色列表</h1>
{% if "/add_users/" in permission_roles %}
<a href="/add_roles/" class="btn btn-primary">添加角色</a>
{% endif %} <table class="table table-bordered table-striped">
<thead>
<tr>
<th>序号</th>
<th>角色</th>
<th>url</th>
{% if ret %}
<th>操作</th>
{% endif %} </tr>
</thead>
<tbody>
{% for roles in roles_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ roles }}</td>
<td>
{% for roles_son in roles.permissions.all %}
{{ roles_son }} &nbsp;, &nbsp;
{% endfor %}
</td> {% if ret %}
<td>
{% if '/delete_roles/(\\d+)/' in permission_roles %}
<a href="/delete_roles/{{ roles.id }}/" class="btn btn-danger">删除</a>
{% endif %} {% if "/edeit_roles/(\\d+)/" in permission_roles %}
<a href="/edeit_roles/{{ roles.id }}/" class="btn btn-warning">编辑</a>
{% endif %}
</td> {% endif %}
</tr>
{% endfor %}
</tbody>
</table> {% endblock %}

{% extends "base.html" %}

{% block con %}
<h4>用户列表</h4> {% if "/add_users/" in permission %}
<a href="/add_users/" class="btn btn-primary">添加用户</a> {% endif %} <table class="table table-bordered table-striped">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>角色</th>
{% if ret %}
<th>操作</th>
{% endif %}
</tr>
</thead>
<tbody> </tbody>
{% for user in user_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.name }}</td>
<td>
{% for role in user.roles.all %}
{{ role.title }}
{% endfor %}
</td>
{% if ret %}
<td>
{% if "/delete_users/(\\d+)/" in permission %}
<a href="/delete_users/{{ user.id }}/" class="btn btn-danger">删除</a>
{% endif %} {% if "/edeit_users/(\\d+)/" in permission %}
<a href="/edeit_users/{{ user.id }}/" class="btn btn-warning">编辑</a>
{% endif %} </td>
{% endif %} </tr> {% endfor %} </table> {% endblock %}

Djiango权限组件的更多相关文章

  1. Django-CRM项目学习(六)-rbac模块(权限组件)

    1.rbac权限组件 1.1 模板分析(五表结构) 1.2 模板构建 人物和角色进行多对多绑定,角色与权限进行多对多绑定.其中人物和角色的多对多绑定的操作可以避免相同的人物多重权限的操作. 1.3 数 ...

  2. Django-CRM项目学习(七)-权限组件的设置以及权限组件的应用

    开始今日份整理 1.利用自定制标签,增加展示权限,权限分级设定 1.1 在权限组件中创建自定义标签 使用自定义标签的目的,使各个数据进行分离 1.2 导入自定义标签包 自定义标签复习(自定义标签有三种 ...

  3. DjangoRestFramework学习三之认证组件、权限组件、频率组件、url注册器、响应器、分页组件

    DjangoRestFramework学习三之认证组件.权限组件.频率组件.url注册器.响应器.分页组件   本节目录 一 认证组件 二 权限组件 三 频率组件 四 URL注册器 五 响应器 六 分 ...

  4. 前后端分离djangorestframework——权限组件

    权限permissions 权限验证必须要在认证之后验证 权限组件也不用多说,读了源码你就很清楚了,跟认证组件很类似 具体的源码就不展示,自己去读吧,都在这里: 局部权限 设置model表,其中的ty ...

  5. rest-framework的权限组件

    权限组件 写在开头: 首先要在models表中添加一个用户类型的字段: class User(models.Model): name=models.CharField(max_length=32) p ...

  6. $Django Rest Framework-认证组件,权限组件 知识点回顾choices,on_delete

    一 小知识点回顾 #orm class UserInfo (models.Model): id = models.AutoField (primary_key=True) name = models. ...

  7. Django的rest_framework的权限组件和频率组件源码分析

    前言: Django的rest_framework一共有三大组件,分别为认证组件:perform_authentication,权限组件:check_permissions,频率组件:check_th ...

  8. Django高级篇三。restful的解析器,认证组件,权限组件

    一.rest=framework之解析器 1)解析器作用. 根据提交的数据.只解析某些特定的数据.非法数据不接收,为了系统安全问题 比如解析的数据格式有 有application/json,x-www ...

  9. python 全栈开发,Day107(CRM初始,权限组件之权限控制,权限系统表设计)

    一.CRM初始 CRM,客户关系管理系统(Customer Relationship Management).企业用CRM技术来管理与客户之间的关系,以求提升企业成功的管理方式,其目的是协助企业管理销 ...

随机推荐

  1. springmvc的注解配置

    springmvc大大减少了对xml的配置,减少了配置量,以及可以在一个controller类中进行多个请求配置 一.springmvc配置 context:component-scan 开启包扫描, ...

  2. Fastjson爆出重大漏洞,攻击者可使整个业务瘫痪

    360网络安全响应中心 https://cert.360.cn/warning/detail?id=82a509e4543433625d6fe4361b5802c9 报告编号:B6-2019-0905 ...

  3. DS 壹之型 头指针与头结点

    之前结合网上博客整理的笔记,希望能帮你解除疑惑!    

  4. 深度探索MySQL主从复制原理

    深度探索MySQL主从复制原理 一 .概要 MySQL Replication (MySQL 主从复制) 是什么? 为什么要主从复制以及它的实现原理是什么? 1.1 MySQL 主从复制概念 MySQ ...

  5. 登录和退出Mysql

    这里介绍的是通过cmd方式登录和退出Mysql的方式 一.登录命令 登录命令:mysql.exe -h主机地址   -P端口   -u用户名    -p密码 即依次输入服务器地址.服务器监听的端口.用 ...

  6. java之初识hibernate

    1. 使用jdbc进行数据库操作:获取数据库连接,编写sql语句,执行sql操作,关闭连接. 比如:每次创建连接,释放资源----使的执行效率降低: 解决方案:连接池. 编写sql语句动作----简单 ...

  7. devextreme组装数据导出excel

    $.get("", function (grid_dataSource) { var grid_config = dxConfig.grid(grid_dataSource); g ...

  8. vue 解决ios编辑器输入框不能拉起

    一.问题描述:Android .pc.下可以正常使用,在ios下可以拉起输入框但是无法输入 <div contenteditable="true" ></div& ...

  9. SAP云平台里的三叉戟应用

    大家第一次看到SAP MTA这个词组,会联想到什么? Jerry第一次看到的时候,联想到的是那一个个足坛著名的三叉戟攻击组合. 海皇波塞冬(Poseidon),奥林匹斯十二神中地位仅次于宙斯的大神,海 ...

  10. spark 机器学习 随机森林 实现(二)

    通过天气,温度,风速3个特征,建立随机森林,判断特征的优先级结果 天气 温度 风速结果(0否,1是)天气(0晴天,1阴天,2下雨)温度(0热,1舒适,2冷)风速(0没风,1微风,2大风)1 1:0 2 ...