一. 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. K8S从入门到放弃系列-(16)Kubernetes集群Prometheus-operator监控部署

    Prometheus Operator不同于Prometheus,Prometheus Operator是 CoreOS 开源的一套用于管理在 Kubernetes 集群上的 Prometheus 控 ...

  2. 《算法 - Lru算法》

    一:概述 - LRU 用于管理缓存策略,其本身在 Linux/Redis/Mysql 中均有实现.只是实现方式不尽相同. - LRU 算法[Least recently used(最近最少使用)] - ...

  3. go 渲染数据到文件

    //把数据写到文件里面 package main import ( "fmt" "text/template" "time" "o ...

  4. ORACLE链接SQLSERVER数据库数据操作函数范例

    ORACLE链接SQLSERVER数据库数据操作函数范例 create or replace function FUN_NAME(LS_DJBH IN varchar2 ,LS_ITM varchar ...

  5. JAVA day1 基础知识

    一.windows命令 dir:查看文件 cd:打开文件 二.java的编译和运行 编译: javac 源文件名 一个类编译后会对应一个.class文件 运行: java 类名 三.类 一个源文件内可 ...

  6. vmware的三种网络模式讲解

    vmware有三种网络设置模式,分别是Bridged(桥接),NAT(网络地址转换),Host-only(私有网络共享主机) 1.Bridged(桥接) 桥接模式默认使用的是:VMnet0 什么是桥接 ...

  7. 5_PHP数组_3_数组处理函数及其应用_1_快速创建数组的函数

    以下为学习孔祥盛主编的<PHP编程基础与实例教程>(第二版)所做的笔记. 一.快速创建数组的函数 1. range() 函数 程序: <?php $numbers = range(1 ...

  8. expect脚本远程登录、远程执行命令和脚本传参简单用法

    expect介绍: 最近想写一个自动化安装脚本,涉及到远程登录.分发文件包.远程执行命令等,其中少不了来回输入登录密码,交互式输入命令等,这样就大大降低了效率,那么有什么方法能解决呢?不妨试试expe ...

  9. Dubbo 高级特性实践-泛化调用

    引言 当后端Java服务用Dubbo协议作为RPC方案的基础,但部分消费方是前端Restful的PHP服务,不能直接调用,于是在中间架设了Router服务提供统一的基于HTTP的后端调用入口. 而Ro ...

  10. 一个97年测试妹纸的成长经历,转正直接涨薪2K

    这篇文章,涉及测试团队管理.测试流程建设.测试从业者能力成长.优秀测试从业者的状态.以及同样是两年的Tester,为何他人如此优秀 . 一切的一切,都是有原因的 . 期望这篇文章,对关注「简尚」公号的 ...