Keep Me Logged In for Django

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# The middleware

    from django.conf import settings
    from datetime import timedelta, date

    class KeepLoggedInMiddleware(object):
        def process_request(self, request):
            if not request.user.is_authenticated() or not settings.KEEP_LOGGED_KEY in request.session:
                return
            if request.session[settings.KEEP_LOGGED_KEY] != date.today():
                request.session.set_expiry(timedelta(days=settings.KEEP_LOGGED_DURATION))
                request.session[settings.KEEP_LOGGED_KEY] = date.today()
            return

# Add to settings
1. unit_name.KeepLoggedInMiddleware to the bottom of MIDDLEWARE_CLASSES
2. 
    KEEP_LOGGED_KEY                   = 'keep_me_logged' # session key
    KEEP_LOGGED_DURATION              = 365         # in days


# In your login view

    form = LoginForm(request.POST)
    
    if form.is_valid():
            # some code

            if form.remember:
                request.session[settings.KEEP_LOGGED_KEY] = True

More like this

  1. Using another memcached for sessions by dipankarsarkar 5 years, 5 months ago
  2. Remember me for login by iElectric 4 years, 2 months ago
  3. StrictAuthentication - Auto log-out inactive users by yeago 5 years, 6 months ago
  4. Clear session data on login and logout by jb0t 6 years ago
  5. Logging to rotating files by davidfung 8 months ago

Comments

darek (on February 22, 2011):

Better choice is to overload login method and add one line which change cookie expiry time:

def login(request, ...):
    #...
    if request.POST.get('remember_me', None):
        request.session.set_expiry(settings.KEEP_LOGGED_DURATION)
    #...

In that case You don't have to write and use middlewares and other stuff.

#

artur_mwaigaryan (on November 8, 2011):

good point @ derek,ur solution is more efficient

#

(Forgotten your password?)