权限设置

1. 表设计

from django.db import models

# Create your models here.

class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    roles = models.ManyToManyField(to='role')

    def __str__(self):
        return self.username


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=64)

    flag = models.CharField(max_length=32, default='list')

    def __str__(self):
        return self.title

2. views视图

from django.shortcuts import render, redirect
from app01 import models
# Create your views here.

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 查询用户账号密码是否正确
        user_obj = models.User.objects.filter(username=username, password=password).first()
        if user_obj:
            # 账号密码无误需要记录用户的登录状态session值
            request.session['username'] = user_obj.username
            # 查询用户所有的url权限, 用户可能函数有不同角色,权限可能有重复,distinct进行去重
            permission_list = user_obj.roles.values('permissions__url').distinct()
            # 将当前用户可以能访问的url记录到session中

            request.session['permission_list'] = [permission.get('permissions__url') for permission in permission_list]


            return redirect('/index/')

    return render(request, 'login.html')


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

3. premission.py(校验数据,中间件)

 

 

import re
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

from django.shortcuts import redirect


class Mypermission(MiddlewareMixin):
    def process_request(self, request):

        # 获取用户想要访问的url
        current_path = request.path    # 获取url的后缀

        # current_path = request.get_full_path() # 获取后缀加get加get请求参数
        # print(current_path)

        # 定义网站的白名单
        white_list = ['/login/', '/register/', '/index/', '/admin/.*']
        # if current_path in white_list:
        #     return None   # 不太完美
        for url in white_list:
            res = re.search(url, current_path)
            if res:
                return None

        # 判断用户是否已经登录
        if not request.session.get('username'):
            return redirect('/login/')

        # 校验用户权限

        permission_list = request.session.get('permission_list')
        # print(permission_list)
        # 判断是否在用户权限内
        # if current_path in permission_list:   # 无法匹配正则
        #     return None

        for permission in permission_list:
            permission = '^%s$' % permission
            res = re.search(permission, current_path)

            if res:
                return None

        return HttpResponse('没有权限')

 

posted on 2019-08-06 22:51  软饭攻城狮  阅读(198)  评论(0编辑  收藏  举报

导航