首页 » Python » python3 高级篇 » 正文

Django框架–自定义中间件权限限制

如上我们 request.session 保存了用户的权限,但是如何去取呢?

自定义中间件(settings中的MIDDLEWARE)

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',
    'auth_server.middleware.cmdb_auth.AuthMiddleware'     ##符合需求即可进行下一步,不符合直接返回!
]

mark

cmdb_auth.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-2-3 12:51
# @Author  : zhdya@zhdya.cn
# @File    : cmdb_auth.py

# from django.utils.deprecation import MiddlewareMixin        ##django新版本不支持这种导入方式
import re
from django.shortcuts import redirect, HttpResponse, render


class MiddlewareMixin(object):  ##此处的代码是从如上导入的MiddlewareMixin 使用ctrl+鼠标左键打开黏贴过来的
	def __init__(self, get_response=None):
		self.get_response = get_response
		super(MiddlewareMixin, self).__init__()

	def __call__(self, request):
		response = None
		if hasattr(self, 'process_request'):
			response = self.process_request(request)
		if not response:
			response = self.get_response(request)
		if hasattr(self, 'process_response'):
			response = self.process_response(request, response)
		return response


VALID_LIST = ['/auth/demo', '/admin/*', '/index.html']		##白名单List


class AuthMiddleware(MiddlewareMixin):

	def process_request(self, request):  ##对进来的请求做处理
		##1.获取当然请求URL (request.path_info)
		##2.获取session中保存的当前用户的权限 request.session.get('permission_url_list')
		current_url = request.path_info  ##当前用户访问的url

		##白名单中url不会做任何的判断!!
		for url in VALID_LIST:
			if re.match(url, current_url):
				return None

		##如果用户没有登录就不会有session,然后就会跳转到登陆;
		auth_dic = request.session.get('auth_dic')  ##获取session字典中的数据
		if not auth_dic:
			return redirect('/auth/demo')
		flag = False
		for group_name, auth_url in auth_dic.items():
			for url in auth_url['url']:
				regax = "^{0}$".format(url)  ##拼接url
				if re.match(regax, current_url):
					##获取当前用户对当前组内的所有code,并赋值给request
					## request.permission_code_list = code_url['url']
					request.permission_code_list = auth_url['url']
					flag = True
					break
			if flag:
				break
		if not flag:
			return HttpResponse('没有权限!!')

当我们再次访问的时候,如果没有任何的session信息就会直接返回 “没有权限”!!

赞 (0)

发表评论