django 权限控制精简版
视图代码:
视图代码 def index(request): return render(request,'index.html') def login(request): if request.method == 'POST': user = request.POST.get('user') pwd = request.POST.get('pwd') user_obj = models.User.objects.filter(username=user,password=pwd).first() #拿用户对象 if not user_obj: return render(request,'login.html',{'error':"用户名或密码错误"}) #登录成功 #查询权限信息 permissions = user_obj.roles.filter(permissions__url__isnull=False).values("permissions__url").distinct() #保存权限信息 request.session['permissions'] = list(permissions) #保存登录状态 request.session['is_login'] = '1' return redirect('/index/') return render(request,'login.html')
当用户登录成功后,获取用户权限,并保存到session中,以前保存登录状态
中间件验证
from django.utils.deprecation import MiddlewareMixin from django.conf import settings from django.shortcuts import HttpResponse,redirect import re class RbacMiddleWare(MiddlewareMixin): def process_request(self,request): url = request.path_info for i in settings.WHITE_LIST: if re.match(i,url): #判断是否是白名单 return #登录状态校验 is_login = request.session.get('is_login') print(is_login) if is_login != '1': return redirect('/login/') #免认证校验 for i in settings.NO_AUTH_LIST: if re.match(i,url): #判断是否是免认证 return #权限校验 permissions = request.session.get('permissions') print(permissions) for i in permissions: if re.match(r'^{}$'.format(i['permissions__url']),url): return return HttpResponse('没有权限,请连线管理员')
白名单和面验证设置 settings文件
WHITE_LIST = [ r'^/login/$', r'^/regist/$', r'^/admin.*/' ] NO_AUTH_LIST = [ r'^/index/$', ]
We are down, but not beaten. tested but not defeated.