第78篇 Django权限系统

Posted cavalier-chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第78篇 Django权限系统相关的知识,希望对你有一定的参考价值。

技术分享图片

1. middleware.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from luffy_permission import settings
import re

class RBACMiddleware(MiddlewareMixin):

    def process_request(self,request):
        # 0. 判断当前访问的url在不在白名单之中
        white_urls = getattr(settings,‘WHITE_URLS‘,[])
        # 判断当前这次请求的URL不在权限里边里面
        # 1. 获取当前请求的url
        current_url = request.path_info
        # 2. 如果是白名单里面的url直接放行
        for url in white_urls:
            if re.match(r‘^{}$‘.format(url),current_url):
                return None
        # if current_url in white_urls:
        #     return None
        # 3. 获取当前这个用户的权限列表
        permission_list = request.session.get(settings.PERMISSION_SESSION_KEY,[])
        for pattern in permission_list:
            if re.match(‘^{}$‘.format(pattern),current_url):
                # 有权限
                return None
        else:
            return HttpResponse(‘没有该权限!!‘)
        # if current_url in permission_list:  # 这种直接in的方式不行 没有经过正则匹配
        #     return None
        # else:
        #     return HttpResponse(‘没有该权限!!‘)

  2. views.py

from django.shortcuts import render,redirect,HttpResponse
from web.models import UserInfo
from luffy_permission import settings
# Create your views here.


def login(request):
    error_msg = ‘‘
    if request.method == ‘POST‘:
        username = request.POST.get(‘username‘)
        pwd = request.POST.get(‘password‘)
        user_obj = UserInfo.objects.filter(username=username,password=pwd).first()
        if user_obj:
            # 登陆成功
            # 1.1 将当前登录用户的权限信息查询出来
            # 1.2 将权限信息保存到session数据中
            # 用户 -->角色 -->权限
            # user_obj.roles.all()  #Queryset
            permission_queryset = user_obj.roles.all().filter(permission__isnull=False).values_list(‘permission__url‘,)
            permission_list = [i[0] for i in permission_queryset]  # [‘/customer/list/‘, ‘/customer/add/‘, ‘/payment/list/‘, ‘/payment/add/‘]
            # print(permission_list)
            request.session[settings.PERMISSION_SESSION_KEY] = permission_list
            return redirect(‘/customer/list/‘)

        else:

            error_msg = ‘用户名或密码错误!!‘
    return render(request,‘login.html‘,{‘error_msg‘:error_msg})


def logout(request):
    request.session.flush()
    return redirect(‘/login/‘)

  3. admin.py

from django.contrib import admin
from web.models import UserInfo,Permission,Role
# Register your models here.


class PermissionAdmin(admin.ModelAdmin):
    list_display = [‘title‘,‘url‘]
    list_editable = [‘url‘]

admin.site.register(UserInfo)
admin.site.register(Permission,PermissionAdmin)
admin.site.register(Role)

  4. setting.py

MIDDLEWARE = [
    ‘django.middleware.security.SecurityMiddleware‘,
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    ‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
    ‘rbac.middleware.RBACMiddleware‘,
]
TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [os.path.join(BASE_DIR, ‘rbac/templates‘)]
        ,
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]
# 权限组件的相关配置
# 白名单
WHITE_URLS = [
    ‘/login/‘,
    ‘/logout/‘,
    ‘/reg/‘,
    ‘/admin/.*‘,
]

# session_key
PERMISSION_SESSION_KEY = ‘permission_url‘

  

以上是关于第78篇 Django权限系统的主要内容,如果未能解决你的问题,请参考以下文章

Django REST框架--认证和权限

Android 逆向Linux 文件权限 ( Linux 权限简介 | 系统权限 | 用户权限 | 匿名用户权限 | 读 | 写 | 执行 | 更改组 | 更改用户 | 粘滞 )(代码片段

django(权限认证)系统—— 基于Authentication backends定制

第61篇 Django 路由系统 正则表达式和二级路由 路由的命名和反向解析

Python代码阅读(第19篇):合并多个字典

Python第5堂课(linux系统之用户群组权限篇)