• 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('超过权限')

  • 相关阅读:
    监控 | open-falcon | 安装
    日语 | 日本50音
    PXE | 开关机
    linux | 网卡驱动
    Linux——Centos 7 chmod命令
    Linux——Centos 7 ls命令
    Linux——Centos 7 passwd命令
    Linux——Centos 7 账户管理命令(用户组篇)groupadd groupmod groupdel
    Linux——Centos 7 账户管理命令(用户篇)useradd usermod userdel
    Linux——Centos 7 diff命令
  • 原文地址:https://www.cnblogs.com/lnrick/p/9758447.html
Copyright © 2020-2023  润新知