day5 crm客户管理权限控制代码优化

需要优化的部分

用户权限初始化代码需要单独放置在一个模块里,且放在rbac目录中
day5 crm客户管理权限控制代码优化
session的key键值需要配置化,在setting文件配置
day5 crm客户管理权限控制代码优化
用户权限校验中间件需要放在权限目录中,不能放置在业务代码中
day5 crm客户管理权限控制代码优化

优化后

优化后项目目录
day5 crm客户管理权限控制代码优化
具体代码
web/views/account.py

from django.shortcuts import HttpResponse, render, redirect
from rbac import models
from rbac.service.init_Permission import init_Permission


def login(request):
    # 1. 用户登录
    if request.method == 'GET':
        return render(request, 'login.html')
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')

    current_user = models.UserInfo.objects.filter(name=user, password=pwd).first()
    if not current_user:
        return render(request, 'login.html', {'msg': '用户名或密码错误'})
    init_Permission(current_user,request)

    return redirect('/customer/list/')

rbac/service/init_Permission.py

# -*- encoding: utf-8 -*-
"""
@File    : init_Permission.py
@Time    : 2021-12-16 22:30
@Author  : tangsai
@Email   : 294168604@qq.com
@Software: PyCharm
"""
from luffy_permission_simon import settings


def init_Permission(current_user, request):
    # 2. 权限信息初始化
    # 根据当前用户信息获取此用户所拥有的所有权限,并放入session。
    # 当前用户所有权限
    permission_queryset = current_user.roles.filter(permissions__isnull=False).values("permissions__id",
                                                                                      "permissions__url").distinct()

    # 获取权限中所有的URL
    # permission_list = []
    # for item in permission_queryset:
    #     permission_list.append(item['permissions__url'])

    permission_list = [item['permissions__url'] for item in permission_queryset]
    # for item in permission_list:
    #     print(item)
    # request.session[settings.PERMISSION_SESSION_KEY] = permission_list
    request.session[settings.PERMISSION_SESSION_KEY] = permission_list

rbac/middlewares/rbac.py

# -*- encoding: utf-8 -*-
"""
@File    : rbac.py
@Time    : 2021-12-16 22:29
@Author  : tangsai
@Email   : 294168604@qq.com
@Software: PyCharm
"""
import re
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from luffy_permission_simon import settings


class RbacMiddleware(MiddlewareMixin):
    """
    用户权限信息校验
    """

    def process_request(self, request):
        """
        当用户请求刚进入时候出发执行
        :param request:
        :return:
        """

        """
        1. 获取当前用户请求的URL
        2. 获取当前用户在session中保存的权限列表 ['/customer/list/','/customer/list/(?P<cid>\\d+)/']
        3. 权限信息匹配
        """
        valid_url_list = [
            '/login/',
            '/admin/.*'
        ]

        current_url = request.path_info
        for valid_url in valid_url_list:
            if re.match(valid_url, current_url):
                # 白名单中的URL无需权限验证即可访问
                return None

        permission_list = request.session.get(settings.PERMISSION_SESSION_KEY)
        if not permission_list:
            return HttpResponse('未获取到用户权限信息,请登录!')

        flag = False

        for url in permission_list:
            reg = "^%s$" % url
            if re.match(reg, current_url):
                flag = True
                break

        if not flag:
            return HttpResponse('无权访问')

setting.py
中间件路径更改
day5 crm客户管理权限控制代码优化
新增配置

#######权限相关配置#######
#session的key键值
PERMISSION_SESSION_KEY = 'luffy_permission_url_list_key'
#白名单路径
VALID_URL_LIST = [
    '/login/',
    '/admin/.*'
]
上一篇:Day5:剑指 Offer 11. 旋转数组的最小数字


下一篇:C语言学习day5-scanf循环读取