2018-10-11 20:30:42
根据用户权限,是否显示权限操作按钮!
其实就是在html页面增加判断是不是用户有权限,有就显示按钮,没有就不显示
然后第一种简单粗暴,直接if url 写死了
第二种 直接多建了几张表解耦,然后各种复杂操作!就是为了解耦不写死!!长远看,很值得学习!
越努力,越幸运!永远不要高估自己!
放上代码
models.py
from django.db import models 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) action = models.CharField(max_length=32,default="") group = models.ForeignKey("PermissionGroup",default=1) def __str__(self): return self.title # 创建一个角色组的表 2018-10-11 17:33:51 class PermissionGroup(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title
rbac/service/persions.py
def initial_session(user,request):
"""用于储存查询到用户权限的session"""
# 方案1
permissions = user.roles.all().values("permissions__url").distinct()
# 【{},{}】
permission_list = []
for item in permissions:
permission_list.append(item["permissions__url"])
print(permission_list)
request.session["permission_list"] = permission_list
# 方案2
permissions = user.roles.all().values("permissions__url","permissions__group_id","permissions__action").distinct()
print("permissions",permissions)
permission_dict={}
for item in permissions:
gid=item.get('permissions__group_id')
if not gid in permission_dict:
permission_dict[gid] = {
"urls": [item["permissions__url"],],
"actions": [item["permissions__action"],]
}
else:
permission_dict[gid]["urls"].append(item["permissions__url"])
permission_dict[gid]["actions"].append(item["permissions__action"])
request.session['permission_dict'] = permission_dict
rbac/service/rabc.py
import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
def reg(request,current_path):
# 校验权限1(permission_list)
permission_list = request.session.get("permission_list", [])
flag = False
for permission in permission_list:
permission = "^%s$" % permission
ret = re.match(permission, current_path)
if ret:
flag = True
break
return flag
class ValidPermission(MiddlewareMixin):
def process_request(self, request):
# 当前访问路径
current_path = request.path_info
# 检查是否属于白名单
valid_url_list=["/login/","/reg/","/admin/.*"]
for valid_url in valid_url_list:
ret=re.match(valid_url,current_path)
if ret:
return None
# 校验是否登录
user_id = request.session.get("user_id")
if not user_id:
return redirect("/login/")
# 校验权限1(permission_list)
permission_list = request.session.get("permission_list",[]) # ['/users/', '/users/add', '/users/delete/(\d+)', 'users/edit/(\d+)']
flag=reg(request,current_path)
if not flag:
return HttpResponse("没有访问权限!")
return None
# 校验权限2
# permission_dict = request.session.get("permission_dict")
#
# for item in permission_dict.values():
# urls=item['urls']
# for reg in urls:
# reg ="^%s$" % reg
# ret=re.match(reg,current_path)
# if ret:
# request.actions=item['actions']
# return None
#
# return HttpResponse("没有访问权限!")
views.py
from django.shortcuts import render,HttpResponse
from rbac01.service.perssions import *
from rbac01.models import *
class Per(object):
def __init__(self,actions):
self.actions=actions
def add(self):
return "add" in self.actions
def delete(self):
return "delete" in self.actions
def edit(self):
return "edit" in self.actions
def list(self):
return "list" in self.actions
def users(request):
user_list=User.objects.all()
# permission_list=request.session.get("permission_list")
# print(permission_list)
# 查询当前登录人得名字
id = request.session.get("user_id")
user = User.objects.filter(id=id).first()
# 创建一个类对象,然后传入前端, 可以直接 per.add 对象调用方法 省事!
per = Per(request.actions)
# locals() 内置函数 返回全局所有变量,生成一个字典,就是{'per': per}的升级版
return render(request, "rbac/users.html", locals())
import re
def add_user(request):
return HttpResponse("add user.....")
def del_user(request,id):
return HttpResponse("del"+id)
def roles(request):
role_list=Role.objects.all()
per = Per(request.actions)
return render(request,"rbac/roles.html",locals())
def login(request):
if request.method=="POST":
user=request.POST.get("user")
pwd=request.POST.get("pwd")
user=User.objects.filter(name=user,pwd=pwd).first()
if user:
############################### 在session中注册用户ID######################
request.session["user_id"]=user.pk
###############################在session注册权限列表##############################
# 查询当前登录用户的所有角色
# ret=user.roles.all()
# print(ret)# <QuerySet [<Role: 保洁>, <Role: 销售>]>
# 查询当前登录用户的所有权限,注册到session中
initial_session(user,request)
# return HttpResponse("登录成功!")
return redirect("/users/")
return render(request,"login.html")
user.html
{% extends 'base.html' %} {% block con %} {% load my_tags %} {% valid '<a href="/users/add/" class="btn btn-primary">添加用户</a>' request %} <h4>用户列表</h4> {% if per.add %} <a href="users/add/" class="btn btn-primary">添加用户</a> {% endif %} <table class="table table-bordered table-striped"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>角色</th> <th>操作</th> </tr> </thead> <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> <td> {% if per.delete %} <a href="/users/delete/{{ user.pk }}" class="btn btn-danger">删除</a> {% endif %} {% if per.edit %} <a href="" class="btn btn-warning">编辑</a> {% endif %} </td> </tr> {% endfor %} </tbody> </table> {% endblock %}
my_stgs.py
# by luffycity.com from django import template register=template.Library() # 解耦 放专门获取用户权限的函数 @register.inclusion_tag("rbac/menu.html") def get_menu(request,): # 获取当前用户可以放到菜单栏中的权限 menu_permission_list = request.session["menu_permission_list"] return {"menu_permission_list":menu_permission_list}
放上笔记
day83: 权限粒度控制 简单控制: {% if "users/add" in permissions_list%} 摆脱表控制 更改数据库结构 class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) # 添加个用户行为 action=models.CharField(max_length=32,default="") # 部门群组 group=models.ForeignKey("PermissionGroup",default=1) def __str__(self):return self.title class PermissionGroup(models.Model): title = models.CharField(max_length=32) def __str__(self): return self.title 登录验证: permissions = user.roles.all().values("permissions__url","permissions__group_id","permissions__action").distinct() 构建permission_dict permissions: [ {'permissions__url': '/users/add/', 'permissions__group_id': 1, 'permissions__action': 'add'}, {'permissions__url': '/roles/', 'permissions__group_id': 2, 'permissions__action': 'list'}, {'permissions__url': '/users/delete/(\d+)', 'permissions__group_id': 1, 'permissions__action': 'delete'}, {'permissions__url': 'users/edit/(\d+)', 'permissions__group_id': 1, 'permissions__action': 'edit'} ] permission_dict { 1: { 'urls': ['/users/', '/users/add/', '/users/delete/(\d+)', 'users/edit/(\d+)'], 'actions': ['list', 'add', 'delete', 'edit']}, 2: { 'urls': ['/roles/'], 'actions': ['list']} } 中间价校验权限: permission_dict=request.session.get("permission_dict") for item in permission_dict.values(): urls=item['urls'] for reg in urls: reg="^%s$"%reg ret=re.match(reg,current_path) if ret: print("actions",item['actions']) request.actions=item['actions'] return None return HttpResponse("没有访问权限!") 思考: 菜单权限显示