權限管理——版本1

權限管理——版本1

1.完成目標:

  1.獲取當前請求的url: 使用 request.path_info
  2.獲取session中的保存的用戶權限: 使用request.session.get().不能request.session[],由於可能沒數據。
  3.設置白名單,獲取到白名單的放行數據,和用戶所擁有的權限url,匹配。 若是匹配,就不須要通過權限的檢查。html

  4.用戶登陸後,把用戶所擁有的url權限和白名單的權限對比。有就能夠直接訪問,沒有就須要通過:權限的判斷。django

  達成的結果:

    1.當前登陸的用戶只有:用戶列表頁面和訂單列表頁面,其它不能訪問。

      

 

    2.不能訪問的頁面:

      

 

2.目錄結構:

    

 

 app01/views.py:session

from django.shortcuts import render,redirect,HttpResponse
from rbac import models
from rbac.service.init_permission import init_permission
import re


def login(reqeust):
    if reqeust.method == 'GET':
        return  render(reqeust,'login.html')
    else:
        user = reqeust.POST.get('user')
        pwd = reqeust.POST.get('pwd')
        print(reqeust.POST)
        user = models.User.objects.filter(username=user,password=pwd).first()
        print(user)
        if not user:
            return render(reqeust,'login.html')
        init_permission(user,reqeust)
        print(111)
        return redirect('/index/')


def index(request):
    print(222)
    return HttpResponse('歡迎登陸   哈哈哈')

def userinfo(request):
    print(2222222)
    return render(request,'index.html')


def userinfo_add(request):

    return HttpResponse('添加用戶頁面')

def order(request):
    return  HttpResponse('訂單頁面')
app01/views.py

 

settings.py:app

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.middlewares.rbac.RbacMiddleware',
    
]

VALID_URL = [
    '/login/',
    '/admin.*/'

]

 

 urls.py:ide

from django.conf.urls import url
from django.contrib import admin

from rbac import views
from app01 import views as app01_views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^test/',views.test),
    url(r'^login/',app01_views.login),
    url(r'^index/',app01_views.index),
    url(r'^userinfo/$',app01_views.userinfo),
    url(r'^userinfo/add',app01_views.userinfo_add),
    url(r'^order/',app01_views.order)


]

 

 rbac.py:post

import re
from permission import settings

from django.shortcuts import redirect,HttpResponse


class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

class RbacMiddleware(MiddlewareMixin):
    def process_request(self,request):
        '''
           1.獲取當前請求的url: 使用  request.path_info
           2.獲取session中的保存的用戶權限: 使用request.session.get().不能request.session[],由於可能沒數據。
           3.設置白名單,獲取到白名單的放行數據,和用戶所擁有的權限url,匹配。 若是匹配,就不須要通過權限的檢查。
             '''
        current_url = request.path_info
        
        for url in settings.VALID_URL:
            if re.match(url,current_url):
                print(url,current_url)
                return None


        permission_list = request.session.get('permissions__url')  # 拿到url格式的數據
        if not permission_list:
            return redirect('/login/')
        flag = False
        for db_url in permission_list:  # 用in不行,含正則的url使用in會匹配不了,所要要用正則:re.match
            regax =  '^{0}$'.format(db_url) #加上起止符,絕對匹配。
            if re.match(regax, current_url):  # 若是匹配成功,就已等
                flag = True
                break
        if not flag:
            return HttpResponse('無權訪問')
rbac.py

 

init_permission.py:ui

def init_permission(user,request):
    '''
    初始化權限信息,把權限url放到session。
    :param user:
    :param request:
    :return:
    '''
    permission_list2 = user.roles.values('permissions__title', 'permissions__url',
                                         'permissions__is_menu').distinct()
    url_list = []
    for item in permission_list2:
        url_list.append(item['permissions__url'])
        print(item['permissions__url'])
    request.session['permissions__url'] = url_list


    #拿到用戶請求url,和session作對比,若是在,可訪問,不在,一邊去。

 

login.html:url

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}
    <p><input type="text" name="user" >用戶名</p>
    <p><input type="password" name="pwd" >密碼</p>
    <input type="submit" value="登陸">
</form>
</body>
</html>
相關文章
相關標籤/搜索