Django “Remember Me” with built-in login view and authentication form

六月ゝ 毕业季﹏ 提交于 2019-11-28 15:44:02
tarequeh

The django session cookie age is defined in seconds.

SESSION_COOKIE_AGE = 360

means that the session will expire after 6 minutes. I've recently implemented the 'Remember Me' feature and I set the following:

SESSION_COOKIE_AGE = 60 * 60 * 24 * 30 # One month

The login view needs override as you've shown in the snippet.

But sounds like you're having an odd issue where closing the browser (when remember me is unchecked) is not requiring the user to re-login which should not happen if you use set_expiry(0). When you use set_expiry(0), the django sets a 'session' length cookie as opposed to a fixed length cookie and by design it would expire after browser close.

There's another settings that affects clearing cookie on browser close. Maybe you can try altering the SESSION_EXPIRE_AT_BROWSER_CLOSE setting's value or check it's existing value in your configuration. https://docs.djangoproject.com/en/2.2/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions

So the request.set_expiry(O) only log in an anonymous but authedicated user.. if i were you,i would do this

if request.user.is_authenticated() and request.user.id is not None: return redirect('home')

Dependencies

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from site_user.models import User

This code will revoke username and password from session when we are at login page

def home(request):
    if request.session.has_key('username') and request.session.has_key('password'):
        username = request.session['username']
        password = request.session['password']
        context_dict = {'username': username, 'password': password}
        return render(request, 'sadmin/login.html', context=context_dict)
    else:
        context_dict = {'username': '', 'password': ''}
        return render(request, 'sadmin/login.html', context=context_dict)

The following code is used for user authentication. Here 'is_remember_check' checkbox field from HTML file

@csrf_exempt
def login(request):
    if request.method == "POST":
        if request.POST['is_remember_check'] == 'true':
            request.session['username'] = request.POST['username']
            request.session['password'] = request.POST['password']

        user = authenticate(username=request.POST['username'], password=request.POST['password'])

        if user is not None:
            return JsonResponse({'result': request.POST, 'status': True})
        else:
            return JsonResponse({'result': request.POST, 'status': False})

AJAX call from login page

function login(){
    remember_checkbox_value = document.getElementsByName('remember')[0].checked;
    username = document.getElementsByName('username')[0].value;
    password = document.getElementsByName('password')[0].value;
    var post_data = {username:username, password:password, is_remember_check:remember_checkbox_value};

    $.ajax({
                url: '/sadmin/login/',
                method: 'POST',
                data: post_data,
                dataType: 'json',
                success: function (response) {
                        if (response.status){
                        alert("User login is successful");
                        window.location.reload();
                        }
                        else{
                        alert("User login is not successful");
                        window.location.reload();
                        }
                }
        });
}

HTML Code

<div class="form-actions">
            <label class="checkbox">
            <input type="checkbox" name="remember"/> Remember me </label>
            <button type="button" class="btn green-haze pull-right" onclick="login()">Login <i class="m-icon-swapright m-icon-white"></i>
            </button>
        </div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!