1. 程式人生 > >Django - CBV裝飾器實現使用者登入驗證 Django 認證裝飾器

Django - CBV裝飾器實現使用者登入驗證 Django 認證裝飾器

一、使用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.html"

但是如果使用類定義的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)

class 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. Django 認證裝飾器