1. 程式人生 > >django rbac權限

django rbac權限

rect value 工程 edit mon opened render set dir

> startapp rbac

models.py

技術分享圖片
from django.db import models

class User(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    roles=models.ManyToManyField(to="Role")

    def __str__(self): return self.name

class Role(models.Model):
    title=models.CharField(max_length=32)
    permissions
=models.ManyToManyField(to="Permission") def __str__(self): return self.title class Permission(models.Model): title=models.CharField(max_length=32) url=models.CharField(max_length=32) def __str__(self):return self.title
View Code

rbac\service包下兩個文件

perssions.py

技術分享圖片
def initial_session(user, request):
    permissions 
= user.roles.all().values("permissions__url").distinct() permission_list = [] for item in permissions: permission_list.append(item["permissions__url"]) print(permission_list) request.session["permission_list"] = permission_list
View Code

rbac.py

技術分享圖片
import re
from django.utils.deprecation import
MiddlewareMixin from django.shortcuts import HttpResponse, redirect class ValidPermission(MiddlewareMixin): def process_request(self, request): # 當前訪問路徑 current_path = request.path_info # 檢查是否屬於白名單 valid_url_list = ["/login/", "/reg/", "/admin/.*"] for valid_url in valid_url_list: ret = re.match(valid_url, current_path) if ret: return None # 校驗是否登錄 user_id = request.session.get("user_id") if not user_id: return redirect("/login/") # 校驗權限 permission_list = request.session.get("permission_list", []) # [‘/users/‘, ‘/users/add‘, ‘/users/delete/(\\d+)‘, ‘users/edit/(\\d+)‘] flag = False for permission in permission_list: permission = "^%s$" % permission ret = re.match(permission, current_path) if ret: flag = True break if not flag: return HttpResponse("沒有訪問權限!") return None
View Code

> startapp app01

views.py

技術分享圖片
from django.shortcuts import render,HttpResponse
from rbac.models import *


def users(request):
    user_list=User.objects.all()

    return render(request,"users.html",locals())


import re
def add_user(request):


    return HttpResponse("add user.....")

def roles(request):

    role_list=Role.objects.all()

    return render(request,"roles.html",locals())
from rbac.service.perssions import *

def login(request):

    if  request.method=="POST":

        user=request.POST.get("user")
        pwd=request.POST.get("pwd")

        user=User.objects.filter(name=user,pwd=pwd).first()
        if user:
            ############################### 在session中註冊用戶ID######################
            request.session["user_id"]=user.pk

            ###############################在session註冊權限列表##############################



            # 查詢當前登錄用戶的所有角色
            # ret=user.roles.all()
            # print(ret)# <QuerySet [<Role: 保潔>, <Role: 銷售>]>

            # 查詢當前登錄用戶的所有權限
            initial_session(user,request)


            return HttpResponse("登錄成功!")


    return render(request,"login.html")
View Code

工程 urls.py

技術分享圖片
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(r^users/$, views.users),
    url(r^users/add, views.add_user),
    url(r^roles/, views.roles),
    url(r^login/, views.login),
]
View Code
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.service.rbac.ValidPermission"
]

django rbac權限