django权限验证装饰器

Posted harrytree

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django权限验证装饰器相关的知识,希望对你有一定的参考价值。

1、模型定义User

from django.db import models
from django.contrib.auth.models import   BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.contrib.auth import get_user_model

class UserManager(BaseUserManager):
    def _create_user(self , telephone, username, password, **kwargs):
        if not telephone:
            raise  ValueError("必须要传递手机号码!")
        if not password:
            raise  ValueError("必须要传递密码")
        user = self.model( telephone = telephone, username= username , **kwargs)
        user.set_password( password )
        user.save()
        return  user

    def create_user(self,  telephone, username, password, **kwargs):
        kwargs[is_superuser] = False
        return self._create_user( telephone = telephone, username=username, password = password, **kwargs )

    def create_superuser(self, telephone, username, password, **kwargs):
        kwargs[is_superuser] = True
        return  self._create_user( telephone = telephone, username=username, password = password, **kwargs )

class User(AbstractBaseUser, PermissionsMixin):
    telephone = models.CharField(max_length=11, unique=True)
    email = models.CharField(max_length=100, unique=True)
    username = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

    USERNAME_FIELD = "telephone"   #USERNAME_FIELD作用,是执行authenticate验证, username参数传入后,实际校验的是telephone字段
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    # author = models.ForeignKey(  User, on_delete= models.CASCADE )
    #get_user_model()会自动获取settings.py里面 AUTH_USER_MODEL,这样不管你定义的那个User,都可以自动获取,更安全
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    class Meta:
        permissions =[
            (view_article, 看文章的权限!),
        ]

2 app01/views.py视图里面,进行权限限制

from django.shortcuts import render, HttpResponse, reverse,redirect
from django.db import  connection
from app01.models import User, Article
from django.contrib.auth import  authenticate, login, logout
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import Permission, ContentType
from app01.forms import LoginForm


def test(request):
    #创建用户
    User.objects.create_user( telephone="15555655555", password="555555", username="zhiliao5" )

    #用认证
    # user = authenticate(request, username="15555655555", password="555555")
    # if user:
    #     print(user.username)
    #     print("验证成功!")
    # else:
    #     print("验证失败!")
    return  HttpResponse("继承AbstractUser扩展用户")


def my_login(request):

    if request.method == "GET":
        return render(request, "login.html")
    else:
        print("提交的数据为:"); print(request.POST)
        form = LoginForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data.get("telephone")
            password = form.cleaned_data.get("password")
            remember = form.cleaned_data.get("remember")
            user = authenticate(request, username =telephone, password=password)
            if user and user.is_active:
                login(request, user)
                if remember:
                    request.session.set_expiry(None)
                else:
                    request.session.set_expiry(0)
                #判断是否有next跳转地址
                if request.GET.get("next"):
                    return redirect( request.GET.get("next") )
                return HttpResponse("登录成功!")
            else:
                return  HttpResponse("手机号码或者密码错误!")
        else:
            print(form.errors)
            return redirect( reverse("login") )

def my_logout(request):
    logout(request)
    return HttpResponse("成功退出")

@login_required(login_url="/login/")
def profile(request):
    return HttpResponse("这是个人中心,只有登录了以后才能查看到!")

#添加权限
def add_permission(request):
    content_type = ContentType.objects.get_for_model( Article)
    permission = Permission.objects.create( codename="black_article", name="拉黑文章", content_type=content_type )
    return HttpResponse("权限创建成功")

#用户与权限
def operate_permission(request):
    user = User.objects.first()
    content_type = ContentType.objects.get_for_model(Article)
    permissions = Permission.objects.filter( content_type = content_type )
    for permission in permissions:
        print(permission)
    #set([])添加权限
    user.user_permissions.set(permissions)
    #清空权限
    # user.user_permissions.clear()
    #add(*[])添加权限
    # user.user_permissions.add(* permissions)
    #remove(*[])删除权限
    # user.user_permissions.remove(*permissions)

    if user.has_perm(app01.view_article):
        print("这个用户拥有view_article权限")
    else:
        print("这个用户没有view_article权限")
    print( user.get_all_permissions())
    return HttpResponse("操作权限的视图!")

#权限限制
# def add_article(request):
#     if request.user.is_authenticated:
#         print("已经登录了")
#         if request.user.has_perm(‘app01.add_article‘):
#             return HttpResponse("这是添加文章的页面!")
#         else:
#             return HttpResponse("您没有访问页面的权限!", status=403)
#     else:
#         return redirect( reverse("login"))

#permission_required做了两件事
#1.如果没有登录,会跳转到登录页面
#2.如果没有权限,通过 raise_exception=True,会显示 403 Forbidden错误页面
@permission_required( app01.add_article, login_url=/login/, raise_exception=True)
def add_article(request):
    return HttpResponse("这是添加文章的页面!")

3、配置路由

from django.contrib import admin
from django.urls import path
from app01 import views as app01_views

urlpatterns = [
    path(admin/, admin.site.urls),
    path("test/", app01_views.test),
    path("login/", app01_views.my_login, name = "login"),
    path("logout/", app01_views.my_logout, name = "logout"),
    path("profile/", app01_views.profile, name="profile"),
    path("add_permission/", app01_views.add_permission, name="add_permission" ),
    path("oper_permission/", app01_views.operate_permission, name="oper_permission" ),
    path("add_article/", app01_views.add_article, name="add_article" ),
]

4、访问add_article,没有登录,会跳转到l “ login/ ”;登录后,但是没有权限,效果如下:

技术图片

 

 

 

 

以上是关于django权限验证装饰器的主要内容,如果未能解决你的问题,请参考以下文章

Python面向对象学习之八,装饰器

装饰器 以及 django 中的应用

Django API 权限装饰器

Django is_staff 权限装饰器

Django-website 程序案例系列-10 验证装饰器

19Django开发总结:自带的常用装饰器应用场景及正确使用方法总结