码迷,mamicode.com
首页 > 其他好文 > 详细

2、rbac组件 后台布局模板,权限粒度控制,权限按钮

时间:2018-08-12 14:15:27      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:filter   重写   time   http   round   html   label   lse   cut   

1、后台布局管理

https://www.cnblogs.com/venicid/p/7772742.html#_label0

1、通用模板

 overflow: auto;       //在a和b模板中进行切换

a 模板 :左侧菜单跟随滚动条
 b模板  左侧以及上不动 ****
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

<style type="text/css"> .header { width: 100%; height: 60px; background-color: #369; } .right { float: right; } .left { float: left; } .menu { position: absolute; top: 60px; left: 0; bottom: 0; background-color: gainsboro; width: 20%; } .content { position: absolute; top: 60px; right: 0; bottom: 0; background-color: mediumpurple; width: 80%; overflow: auto; //在a和b模板中进行切换 } </style> </head> <body> <div class="header"></div> <div class="container"> <div class="menu left"> 1111 </div> <div class="content right">222 {% block content %} {% endblock %} </div> </div> </body> </html>

技术分享图片

 

2、模板继承

users.html / roles.html 继承自 base.html

users.html

{% extends ‘base.html‘ %}

{% block con %}
<h4>用户列表</h4>
    {% for user in user_list %}
    <p>{{ user }}</p>
    {% endfor %}
    
{% endblock con%}

技术分享图片

 

 2、权限按钮控制:简单控制

用户权限不同,按钮显示就不同!

登录成功后,就已经注册了session
request.session[‘permission_list‘] = permission_list

permission_list = request.session.get(‘permission_list‘)

    简单控制:
        {% if "users/add" in permissions_list%} 

技术分享图片

技术分享图片

技术分享图片

 

 

 

 3、修改表结构

BUT: 不好,不想让 if "/users/add/" 写死,会有 "/roles/add/" 情况,不健壮!怎么办?      不应该根据表名,去判断!! 
权限不同,按钮显示就不同 如何做呢?    
上面问题的解决办法:
  为了扩展,
  # 把两条线 合成一个线
  /users/..
   /roles/...

1、admin显示字段

注意:list_display = []

技术分享图片

技术分享图片

 

2、添加action,group字段

注意点:
加了一个权限组表,
将每张表的增删改查,划到一个组里面!
无论多复杂的,最终一定是对数据库的(增删改查)

修改表结构,重新处理中间件,登录页面:
目的:全是为了按钮的粒度,同一个模板,同一个视图,
显示不同的数据,权限

 技术分享图片

技术分享图片
from 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)
    action = models.CharField(max_length=32, default="")

    group = models.ForeignKey(to="PermissionGroup", on_delete=True)
    def __str__(self):
        return self.title


class PermissionGroup(models.Model):
     title = models.CharField(max_length=32 )
     def __str__(self):
         return self.title
View Code

 

技术分享图片技术分享图片

技术分享图片 技术分享图片

 

4、重构数据结构

1、登录验证

 技术分享图片

2、构建permission_dict

3.登录之后,重写 initial_session(user,request)
就是:
# 在session中注册权限列表 用户权限
# request.session[‘permission_list‘] = permission_list

不应该是list 而是dict

# 在session中注册权限字典
request.session[‘permission_dict‘] = permission_dict

 注意点:

permission = user.roles.all().values(‘permission__url‘, ‘permission__group_id‘, ‘permission__action‘).distinct()

  对数据的处理,以组为键


{1: {‘urls‘: [‘/users/‘, ‘/users/add/‘, ‘/users/delete/(\\d+)/‘, ‘/users/edit/(\\d+)/‘], 
     ‘actions‘: [‘list‘, ‘add‘, ‘delete‘, ‘edit‘]}, 
 2: {‘urls‘: [‘/roles/‘], 
     ‘actions‘: [‘list‘]}}

 

技术分享图片

技术分享图片
# -*- coding: utf-8 -*-
# @Time    : 2018/08/11 0011 9:24
# @Author  : Venicid


def initial_session(request,user):
    # 方案2
    permissions = user.roles.all().values("permissions__url", "permissions__group_id","permissions__action").distinct()
    print(permissions)
    # <QuerySet [{‘permissions__url‘: ‘/users/‘,
                # ‘permissions__group_id‘: 1,
                # ‘permissions__action‘: ‘list‘}]>

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

    print(permission_dict)  # {1: {‘urls‘: [‘/users/‘], ‘actions‘: [‘list‘]}}
    request.session["permission_dict"] = permission_dict


    # 方案1:
    """
    permissions = user.roles.all().values("permissions__url").distinct()

    permission_list = []
    for item in permissions:
        permission_list.append(item[‘permissions__url‘])

    print(permission_list)  # [‘/users/‘, ‘/users/add‘, ‘/users/delete/(\\d+)‘, ‘/users/edit/(\\d+)‘]

    request.session["permission_list"] = permission_list
    """

    """
    values :

    for role in user.roles.all():   # <QuerySet [<Role: 保洁>, <Role: 销售>]>
        temp.append({
        "title":role.title,
        "permissions_url":role.permissions.all()
        })

    # <QuerySet [{‘title‘: ‘保洁‘, ‘permissions__url‘: ‘/users/‘},
    # {‘title‘: ‘销售‘, ‘permissions__url‘: ‘/users/‘},
    # {‘title‘: ‘销售‘, ‘permissions__url‘: ‘/users/add‘}]>

    """
View Code

 

 

 

5、限制权限粒度

1、中间件校验权限:

    # 注意:妙 !!
request.actions = item["actions"]

技术分享图片    

技术分享图片  技术分享图片

技术分享图片
# -*- coding: utf-8 -*-
# @Time    : 2018/08/11 0011 9:04
# @Author  : Venicid

import re

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect


class ValidPermission(MiddlewareMixin):
    def process_request(self, request):

        # 当前访问路径
        current_path = request.path_info

        # 1、检验是否属于白名单  白名单,不需要任何权限的url
        # 正则匹配
        valid_url_list = [/login/, /reg/, /admin/.*]
        for valid_url in valid_url_list:
            ret = re.match(valid_url, current_path)

            if ret:
                return None

        # 2、校验是否登录
        user_id = request.session.get("user_id")
        if not user_id:
            return redirect(/login/)

        # 3、校验权限2

        permission_dict = request.session.get("permission_dict", {})
        # {1: {‘urls‘: [‘/users/‘], ‘actions‘: [‘list‘]}}

        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("没有访问权限")

        # 3、校验权限1
        """
        permission_list = request.session.get("permission_list",[])
        print(permission_list)

        flag = False
        for permission in permission_list:
            permission = "^%s$" % permission
            # print(111111111,permission)
            # print(current_path)
            ret = re.match(permission, current_path)
            if ret:
                flag = True
                break

        if not flag:
            return HttpResponse("没有访问权限")
        return None
        """
rbac中间件

 

 

模板层,权限按钮控制

技术分享图片

技术分享图片

技术分享图片

2:用类来实现!!

技术分享图片

技术分享图片
from django.shortcuts import render, HttpResponse

# Create your views here.

from rbac.models import *
from rbac.service.perssions 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")

    # 查询当前登录人的名字
    id = request.session.get("user_id")
    user = User.objects.filter(id=id).first()
    print(user)

    per = Per(request.actions)

    return render(request, "users.html", locals())


def add_user(request):
    return HttpResponse(add user)


def delete_user(request, id):
    return HttpResponse(delete_user)


def edit_user(request, id):
    return HttpResponse(edit_user)


def roles(request):
    role_list = Role.objects.all()

    per = Per(request.actions)
    print(request.actions)
    return render(request, "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中注册用户
            request.session[user_id] = user.pk

            ############# 在session中注册权限list
            initial_session(request, user)

            return HttpResponse("登录成功")

    return render(request, login.html, locals())
View

 

技术分享图片

技术分享图片

 

3、效果

不同的用户,具有不同的权限,

权限不同,显示的按钮就不同!!

 技术分享图片

 

2、rbac组件 后台布局模板,权限粒度控制,权限按钮

标签:filter   重写   time   http   round   html   label   lse   cut   

原文地址:https://www.cnblogs.com/venicid/p/9462452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!