Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django User Sessions, Cookies and Timeout

I'm working with a Django application and my current goal is to keep track of the user session with cookies. I have a feeling that, as always, my understanding is a bit off with regards to how I do this.

For starters, I would like to manage how long it has been since a user has logged in, that way I can successfully log them out if they haven't visited a new page in "x" hours. I am not sure what exactly is standard (for a social network).

Is this information I store on my server? Do cookies actually have any relevancy here? I've used cookies before to store things like a user's timezone, but I am struggling to deal with how I keep track of the user.

All I currently have in terms of user back end is from the django.contrib.auth package.

The only thing I really know how to do in terms of "grabbing" the user's info is done by using statements like if request.user.is_authenticated(): (etc.).

I realize this is somewhat of a complex question, so I will try and narrow it down:

How do I extend my existing information about the current user to capture "last activity" so I can log him/her out if they haven't been using the site in a certain period of time? Do I need to define a custom user model?

My next step after is to create a different type of user, so I feel like I need to make custom user models - beyond just extending the normal user form to make a profile etc.

Thanks for your understanding,

I know I can be confusing when I don't understand things.

Thanks for your time,

James

like image 861
jdero Avatar asked Mar 24 '23 02:03

jdero


1 Answers

You can configure the session middleware for logging out the user automatically, configure the SESSION_COOKIE_AGE, to some low value, and provide the SESSION_SAVE_EVERY_REQUEST, as True.

This will automatically logout the user after certain inactivity, without any need of extending the profile.

 SESSION_COOKIE_AGE
 Default: 1209600 (2 weeks, in seconds)
 >> The age of session cookies, in seconds.

 SESSION_SAVE_EVERY_REQUEST
 Default: False
 >> Whether to save the session data on every request. 
 If this is False (default), then the session data will only be saved if it has been modified – that is, if any of its dictionary values have been assigned or deleted.

And for creating custom/extending User Profile, Django 1.5, comes with configurable User model, please check the docs for examples.

like image 66
Viren Rajput Avatar answered Apr 01 '23 11:04

Viren Rajput