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/ ”;登录后,但是没有权限,效果如下:

原文地址:https://www.cnblogs.com/harryTree/p/11825950.html

时间: 2024-10-03 22:38:54

django权限验证装饰器的相关文章

django登陆验证装饰器

登陆成功返回内层函数结果 outer(func):     wrapper(request, *args, **kwargs):         is_login = request.session.get(, )         is_login:             func(request, *args, **kwargs)         :             redirect()     wrapper

Struts开发一个权限验证拦截器来判断用户是否登录

开发一个权限验证拦截器来判断用户是否登录 当用户请求受保护资源时,先检查用户是否登录 如果没有登录,则向用户显示登录页面 如果已经登录,则继续操作 实现步骤 开发权限验证拦截器 在配置文件中定义拦截器并引用它 开发权限验证拦截器 public class AuthInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation) throws Exception { //获取

flask中权限访问装饰器

根据session里面保存的管理员id查询出对于的角色,根据角色查询出权限,根据权限查询出能够访问的路径 # 权限控制装饰器def admin_auth(f): @wraps(f) def decorated_function(*args, **kwargs): # 让某个函数来继承我们的参数 admin = Admin.query.join( Role ).filter( Role.id == Admin.role_id, Admin.id == session['admin_id'] ).f

Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码

本问主要介绍asp.net的身份验证机制及asp.net MVC拦截器在项目中的运用.现在让我们来模拟一个简单的流程:用户登录>权限验证>异常处理 1.用户登录 验证用户是否登录成功步骤直接忽略,用户登录成功后怎么保存当前用户登录信息(session,cookie),本文介绍的是身份验证(其实就是基于cookie)的,下面看看代码. 引入命名空间 using System.Web.Security; Users ModelUser = new Users() { ID = 10000, Nam

Django View使用装饰器捕获数据库连接异常

"来不及解释了",直接上代码. from django.shortcuts import render, redirect from models import Hosts from django import forms # Create your views here. def database_error(request, message):     if message == '' or message is None:         message = 'Error det

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

FBV装饰器: def auth(func): #装饰器函数 def inner(request, *args, **kwargs): v = request.COOKIES.get('username') if not v: return redirect('/log/') return func(request, *args, **kwargs) return inner 使用方法: 在函数上加上@auth CBV装饰器: 第一种方式:利用django自带的工具 def auth(func)

基于Django-Cookie的CBV和FBV的用户验证装饰器

FBV模式 def cookie(func):       def deco(request,*args,**kwargs):             u = request.get_signed_cookie('username', salt='user', default=None)           if not u:               return render(request,'login.html')           return func(request,*args

Django中decorators装饰器的使用

1.CBV实现的登录视图 class LoginView(View): def get(self, request): """ 处理GET请求 """ return render(request, 'login.html') def post(self, request): """ 处理POST请求 """ user = request.POST.get('user') pwd = re

Django基于Cookie装饰器实现用户认证

def login(request): if request.method =="GET": return render(request,"login.html") elif request.method == "POST": u = request.POST.get("user") p = request.POST.get("password") print(u,p) if u ==user and p