django 框架之 权限篇

1.采用RCBA的方式

用户表,权限表,角色表

当一个用户访问URL,先登录,当登录后拿到这个用户的角色和权限

当用户去访问其他的URL的时候,判断这个URL是否有这个权限,有就可以访问,没有就不让访问

在中间件里面创建白名单,可以让用户访问的页面

 

第一步创建表:

from django.db import models

# Create your models here.
# 用户表
class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    roles = models.ManyToManyField('Role')

    def __str__(self):
        return self.name
# 权限表
class Role(models.Model):
    title = models.CharField(max_length=32)
    permissions = models.ManyToManyField('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


----
在Terminal执行: python  manage.py  makemigrations
在Terminal执行: python  manage.py  migrate

第二步:使用django中的admin添加数据

from django.contrib import admin

# Register your models here.

from project import models

class PermissionAdmin(admin.ModelAdmin):
    list_display = ['pk', 'title', 'url']

class RoleAdmin(admin.ModelAdmin):
    list_display = ['pk', 'title']

admin.site.register(models.User)
admin.site.register(models.Role)
admin.site.register(models.Permission, PermissionAdmin)


在pycharm 中的Terminal创建超级用户:

python manage.py createsuperuser 

第三步骤:将用户名和session放入到session

from django.shortcuts import render,HttpResponse,redirect
from project import models

# Create your views here.

def login(request):

    if request.method == 'POST':
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')

        user_obj = models.User.objects.filter(name=name, pwd=pwd).first()
        # 如果有用户,代表着登录成功
        if user_obj:
            # 写入session
            request.session['user'] = user_obj.name

            per_obj = models.Permission.objects.filter(role__user__name=user_obj.name).distinct()
            permisson_list = [i.url for i in per_obj]

            request.session['permission_list'] = permisson_list

            return HttpResponse('登录成功')
        else:
            return redirect('login')
    else:
        # return HttpResponse('ok')
        return render(request, 'login.html')

第四步:与project同级建立中间件 middleware.py,同时在settings.py中的MIDDLEWARE,加入中间件:

'utils.middleware.PermissionMiddleWare',
import re
from django.shortcuts import HttpResponse,render,redirect
from django.utils.deprecation import MiddlewareMixin

class PermissionMiddleWare(MiddlewareMixin):

    def process_request(self, request):

        for i in ['/login/', '/admin/.*']:
            ret = re.search(i, request.path)
            if ret:
                return None

        #登录认证
        user = request.session.get('user')
        if not user:
            return redirect('login')

        #认证
        for item in request.session['permission_list']:
            print(item)
            print(request.path)
            reg = '^%s$'%item
            ret = re.search(reg, request.path)
            if ret:
                return None
        else:
            return HttpResponse('没有权限')

 

你可能感兴趣的:(django)