1. 程式人生 > >Django基礎之Session版登入驗證

Django基礎之Session版登入驗證

from functools import wraps

def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next_url = request.get_full_path()
        if request.session.get("user"):
            return func(request, *args, **Kwargs)
        else: 
            return redirect("/login/?next={}".format(next_url))
    return inner

def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        
        if username == "yang" and password = "123":
            # 設定session
            request.session["user"] = user
            #獲取跳到登入頁面之前的URL
            next_url = request.GET.get("next")
            # 如果有,就跳轉到登入之前的URL
            if next_url:
                return redirect(next_url)
            # 否則預設跳轉到index頁面
            else:
                return redirect("/index/")
    return render(request, "login.html")
    


@check_login
def logout(request):
    # 刪除所有當前請求相關的session
    request.session.delete()
    return redirect("/login/")
    
@check_login
def index(request):
    current_user = request.session.get("user", None)
    return render(request, "index.html", {"user": currrent_user})