1.建立表關係
2.基於admin錄入數據
3.校驗權限(中間件的應用)
1.建立表關係
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length=32)
password = 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)
urls = models.CharField(max_length=32)
def __str__(self):
return self.title
2.基於admin錄入數據
from django.shortcuts import render, HttpResponse
# Create your views here.
from rbac import models
def user(request):
ret = models.User.objects.all()
return render(request, 'user.html', locals())
import re
def user_add(request):
permission_list = request.session['permission_list'] # ['/user/add', '/user/', '/role/', '/user/delete/(\\d+)', '/user/edit/(\\d+)']
current_path = request.path_info
flag = False
for permission in permission_list:
permission = '^{}$'.format(permission)
ret = re.match(permission, current_path)
if ret:
flag = True
break
if not flag:
return HttpResponse('沒有權限')
return HttpResponse('add_user')
def role(request):
return HttpResponse('add_user')
from rbac.service.permission import *
def login(request):
if request.method == 'POST':
user = request.POST.get('user')
pwd = request.POST.get('pwd')
user = models.User.objects.filter(name=user, password=pwd).first()
if user:
# 在session中註冊用戶id
request.session['user_id'] = user.pk
initial_session(user, request)
return HttpResponse('登錄成功')
# rbac role-based access control
return render(request, 'login.html')
3.校驗權限(中間件的應用)
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
import re
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[
'permission_list'] # ['/user/add', '/user/', '/role/', '/user/delete/(\\d+)', '/user/edit/(\\d+)']
current_path = request.path_info
flag = False
for permission in permission_list:
permission = '^{}$'.format(permission)
ret = re.match(permission, current_path)
if ret:
flag = True
break
if not flag:
return HttpResponse('沒有權限')
return None