crm 權限設計
阿新 • • 發佈:2019-03-20
pri ble white char 名稱 cati 分享圖片 bubuko from
先在項目中創建 app rbac的models.py
from django.db import models class Permission(models.Model): """ 權限表 """ url = models.CharField(‘權限‘, max_length=32) title = models.CharField(‘標題‘, max_length=32) def __str__(self): return self.title class Role(models.Model):""" 角色表 """ name = models.CharField(‘角色名稱‘, max_length=32) permissions = models.ManyToManyField(‘Permission‘, verbose_name=‘角色所擁有的權限‘, blank=True) def __str__(self): return self.name class User(models.Model): """ 用戶表 """ name = models.CharField(‘用戶名‘, max_length=32) pwd = models.CharField(‘密碼‘, max_length=32) roles = models.ManyToManyField(‘Role‘, verbose_name=‘用戶所擁有的角色‘, blank=True) def __str__(self): return self.name
先在web urls.py中添加路由
url(r‘^admin/‘, admin.site.urls), url(r‘^login/$‘, auth.login,name=‘login‘), url(r‘^index/$‘, auth.index,name=‘index‘),
web app 中 views auth.py
from django.shortcuts import render, redirect, HttpResponse, reverse from rbac import models 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‘) # 去數劇庫進行篩選 obj = models.User.objects.filter(name=user, pwd=pwd).first() if not obj: return render(request, ‘login.html‘) permission_query = obj.roles.filter(permissions__url__isnull=False).values(‘permissions__url‘, ‘permissions__title‘).distinct() print(‘1111‘,permission_query) # <QuerySet [{‘permissions__url‘: ‘/index/‘, ‘permissions__title‘: ‘首頁‘}]> request.session[‘permission‘] = list(permission_query) request.session[‘is_login‘] = True return redirect(reverse(‘index‘)) return render(request, ‘login.html‘)
在rbac app中創建過濾器
middlewares/rbac.py
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, redirect, reverse from django.conf import settings import re class RbacMiddleWare(MiddlewareMixin): def process_request(self, request): # 獲取當前訪問的頁面 url = request.path_info # index # 白名單 for i in settings.WHITE_LIST: if re.match(i, url): return # 獲取登錄狀態 is_login = request.session.get(‘is_login‘) # 沒有登錄跳轉到登錄頁面 if not is_login: return redirect(reverse(‘login‘)) # 免認證 for i in settings.NO_PERMISSION_LIST: if re.match(i, url): return # 獲取當前用戶的權限 permission_list = request.session[‘permission‘] print(permission_list) # 權限的校驗 for i in permission_list: if re.match(‘^{}$‘.format(i[‘permissions__url‘]), url): return # 沒匹配成功 沒有權限 return HttpResponse(‘沒有訪問的權限‘)
其中的re 是 引用settings.py中的變量
# 白名單 WHITE_LIST = [ r‘^/login/$‘, r‘^/reg/$‘, r‘^/admin/.*‘, ] # 免認證的地址 需要登錄 不行權限校驗 NO_PERMISSION_LIST = [ ‘/index/‘ ]
附上admin的py
from django.contrib import admin from rbac import models # Register your models here. class PermissionAdmin(admin.ModelAdmin): list_display = [‘url‘, ‘title‘] list_editable = [‘title‘] admin.site.register(models.Permission, PermissionAdmin) admin.site.register(models.Role) admin.site.register(models.User)
crm 權限設計