django crm 项目权限登录

在admin中的操作:
先引入models
定义类:
class PermissionAdmin(admin.ModelAdmin):
list_display = ['title','url'] 显示的的字段
list_editable = ['url']   可以编辑字段
admin.site.register(models.Permission,PermissionAdmin) 在编辑字段的
时候加上
admin.site.register(models.UserInfo)
admin.site.register(models.Role)
权限:在login函数中将url封装到session:
from django.shortcuts import render, redirect,HttpResponse
from django.conf import settings
from rbac import models
 
def login(request):
    if request.method == 'POST':
        nameuser = request.POST.get('username')
        password = request.POST.get('password')
        user = models.UserInfo.objects.filter(name=nameuser,password=password).first()
        if not user:
            return render(request,'login.html',{'err_msg':'您的账户或者密码不正确'})
        permission_list = user.roles.filter(permissions__url__isnull=False).values('permissions__url').distinct()
        request.session[settings.PERMISSION_SESSION_KEY] = list(permission_list)   #这里的在settings进行配置,共用的  ,对session 进行封装
        request.session[settings.USER_INFO] = {'name':nameuser,'id':user.id}
        return redirect('/customer/list/')
    return render(request,'login.html')
 
在中间件中:
from django.shortcuts import render, redirect, HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
import re
 
 
class RbacperpermissionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        url_path = request.path_info  #获取到当前的url
        permission_list = request.session.get(settings.PERMISSION_SESSION_KEY)
#获取到session封装的url,注意是列表套字典
 
        for i in settings.VALID_URL_LIST:  #这里是进行添加白名单
            if re.match(i, url_path):
                return
 
        falg = False
        for permission in permission_list:
            reg = permission['permissions__url']
            if re.match('^%s$' % reg, url_path):  #使用match,有则输出,无则为Nnone
                falg = True
        if not falg:
            return HttpResponse('超过权限')

posted @ 2018-10-09 09:17  又见芳踪  阅读(198)  评论(0编辑  收藏  举报