django之基于cookie和装饰器实现用户认证

Posted 诛仙物语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django之基于cookie和装饰器实现用户认证相关的知识,希望对你有一定的参考价值。

一、使用Django自带的decorator

通常情况,使用 函数定义的view,可以直接使用 login_required 直接装饰

技术分享图片
@login_required
def index(request):
    if request.method == "GET":
        return render(request, "index.htm")


def user_login(request):
    if request.method == "GET":
        return render(request, "login.html")
    if request.method == "POST":
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user_obj = authenticate(username=username, password=password)
        if user_obj:
            login(request, user_obj)
            return redirect(request.GET.get("nex", "/"))
        else:
            return render(request, "login.html")


def user_logout(request):
    logout(request)
    return render(request, "login.html")
技术分享图片

这里需要注意的是: login_required默认会重定向到 /account/login url, 因此我们可以在Settings.py中修改这个默认的重定向url;

LOGIN_URL = "/login/"

 

但是如果使用类定义的view,是不能够直接使用 login_required进行装饰的

需要定义一个 LoginRequired类

技术分享图片
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator


class LoginRequiredMixin(object):
    @method_decorator(login_required(login_url="/login/"))
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
技术分享图片

 

然后在view中进行继承

xxxView(LoginRequired, View)

  pass

 

二、自己写一个认证decorator

函数装饰器

技术分享图片
# 认证装饰器
class AuthDecorator(object):
    @method_decorator(login_required(login_url="/login/"))
    def dispatch(self, request, *args, **kwargs):
        return super(AuthDecorator, self).dispatch(request, *args, **kwargs)


def has_auth(func):
    def auth(request, *args, **kwargs):
            if not request.session.get("username"):
                return redirect(reverse("login"))
            return func(request, *args, **kwargs)
    return auth


@has_auth
def index(request):
    user = request.session.get("username")
    business_obj = Business.objects.all()
    user_obj = User.objects.all()
    hosts = Host.objects.filter(user__username=user)
    return render(request, "index.html", {
        "hosts": hosts,
        "business_obj": business_obj,
        "user_obj": user_obj
    })
技术分享图片

 

类装饰器

技术分享图片
# 认证装饰器
class Auth(View):
    def dispatch(self, request, *args, **kwargs):
        user_obj = UserInfo.objects.filter(username=request.session.get("username")).first()
        if not user_obj:
            return redirect(reverse("login"))
        return super(Auth, self).dispatch(request, *args, **kwargs)


# 主页视图
class IndexView(Auth):
    def get(self, request):
        user = request.session.get("username")
        business_obj = Business.objects.all()
        user_obj = UserInfo.objects.all()
        hosts = Host.objects.filter(user__username=user)
        return render(request, "index.html", {
            "hosts": hosts,
            "business_obj": business_obj,
            "user_obj": user_obj
        })
技术分享图片
 
 
 

 

 

示例1

技术分享图片
 1 # Create your views here.
 2 user = "a"
 3 pwd = "a"
 4 def login(request):
 5     if request.method =="GET":
 6         return render(request,"login.html")
 7     elif request.method == "POST":
 8         u = request.POST.get("user")
 9         p = request.POST.get("password")
10         print(u)
11         print(p)
12         if u ==user and p ==pwd:
13             res = redirect("/index")
14             res.set_cookie(‘user‘,u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
15             return res
16         else:
17             return  render(request,"login.html")
18 def index(request):
19     v = request.COOKIES.get("user")
20     if v:
21         return render(request,"index.html",{"current_user":v})
22     else:
23         return redirect("/login")
技术分享图片

示例2   ---   基于装饰器实现用户认证

 

技术分享图片
 1 user = "a"
 2 pwd = "a"
 3 
 4 def auth(func):
 5     def inner(reqeust,*args,**kwargs):
 6         v = reqeust.COOKIES.get(‘user‘)
 7         if not v:
 8             return redirect(‘/login‘)
 9         return func(reqeust, *args,**kwargs)
10     return inner
11 
12 def login(request):
13     if request.method =="GET":
14         return render(request,"login.html")
15     elif request.method == "POST":
16         u = request.POST.get("user")
17         p = request.POST.get("password")
18         if u ==user and p ==pwd:
19             res = redirect("/index")
20             res.set_cookie(‘user‘,u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
21             return res
22         else:
23             return  render(request,"login.html")
24 @auth
25 def index(request):
26     v = request.COOKIES.get("user")
27     return render(request,"index.html",{"current_user":v})
技术分享图片

以上是关于django之基于cookie和装饰器实现用户认证的主要内容,如果未能解决你的问题,请参考以下文章

CSIC_716_20200113Django入门---forms组件session和cookie登录认证装饰器

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

Django 之装饰器实现登录认证

Django-7

Django之用户认证Auth组件

django的auth认证,is_authenticate 和装饰器的2个方法,注销的功能,