权限管理——版本1
1.完成目标:
1.获取当前请求的url: 使用 request.path_info
2.获取session中的保存的用户权限: 使用request.session.get().不能request.session[],因为可能没数据。
3.设置白名单,获取到白名单的放行数据,和用户所拥有的权限url,匹配。 如果匹配,就不需要经过权限的检查。
4.用户登录后,把用户所拥有的url权限和白名单的权限对比。有就可以直接访问,没有就需要经过:权限的判断。
达成的结果:
1.当前登录的用户只有:用户列表页面和订单列表页面,其它不能访问。
2.不能访问的页面:
2.目录结构:
app01/views.py:
from django.shortcuts import render,redirect,HttpResponse from rbac import models from rbac.service.init_permission import init_permission import re def login(reqeust): if reqeust.method == ‘GET‘: return render(reqeust,‘login.html‘) else: user = reqeust.POST.get(‘user‘) pwd = reqeust.POST.get(‘pwd‘) print(reqeust.POST) user = models.User.objects.filter(username=user,password=pwd).first() print(user) if not user: return render(reqeust,‘login.html‘) init_permission(user,reqeust) print(111) return redirect(‘/index/‘) def index(request): print(222) return HttpResponse(‘欢迎登录 哈哈哈‘) def userinfo(request): print(2222222) return render(request,‘index.html‘) def userinfo_add(request): return HttpResponse(‘添加用户页面‘) def order(request): return HttpResponse(‘订单页面‘)
settings.py:
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01.apps.App01Config‘, ‘rbac.apps.RbacConfig‘ ] 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.middlewares.rbac.RbacMiddleware‘, ] VALID_URL = [ ‘/login/‘, ‘/admin.*/‘ ]
urls.py:
from django.conf.urls import url from django.contrib import admin from rbac import views from app01 import views as app01_views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^test/‘,views.test), url(r‘^login/‘,app01_views.login), url(r‘^index/‘,app01_views.index), url(r‘^userinfo/$‘,app01_views.userinfo), url(r‘^userinfo/add‘,app01_views.userinfo_add), url(r‘^order/‘,app01_views.order) ]
rbac.py:
import re from permission import settings from django.shortcuts import redirect,HttpResponse class MiddlewareMixin(object): 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 class RbacMiddleware(MiddlewareMixin): def process_request(self,request): ‘‘‘ 1.获取当前请求的url: 使用 request.path_info 2.获取session中的保存的用户权限: 使用request.session.get().不能request.session[],因为可能没数据。 3.设置白名单,获取到白名单的放行数据,和用户所拥有的权限url,匹配。 如果匹配,就不需要经过权限的检查。 ‘‘‘ current_url = request.path_info for url in settings.VALID_URL: if re.match(url,current_url): print(url,current_url) return None permission_list = request.session.get(‘permissions__url‘) # 拿到url格式的数据 if not permission_list: return redirect(‘/login/‘) flag = False for db_url in permission_list: # 用in不行,含正则的url使用in会匹配不了,所要要用正则:re.match regax = ‘^{0}$‘.format(db_url) #加上起止符,绝对匹配。 if re.match(regax, current_url): # 如果匹配成功,就已等 flag = True break if not flag: return HttpResponse(‘无权访问‘)
init_permission.py:
def init_permission(user,request): ‘‘‘ 初始化权限信息,把权限url放到session。 :param user: :param request: :return: ‘‘‘ permission_list2 = user.roles.values(‘permissions__title‘, ‘permissions__url‘, ‘permissions__is_menu‘).distinct() url_list = [] for item in permission_list2: url_list.append(item[‘permissions__url‘]) print(item[‘permissions__url‘]) request.session[‘permissions__url‘] = url_list #拿到用户请求url,和session做对比,如果在,可访问,不在,一边去。
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <p><input type="text" name="user" >用户名</p> <p><input type="password" name="pwd" >密码</p> <input type="submit" value="登录"> </form> </body> </html>