Django, setting cookie - django

Django: Cookie set to expire in 30 seconds is actually expiring in 30 minutes? does
hr = HttpResponse('ok')
hr.set_cookie('user_id', user_id, max_age=30)
while https://stackoverflow.com/a/25179642/433570 does
request.session[user_id] = True
And both says we are setting cookie.
What's the difference between the two?
Can I set the expiration with the request.session method?

In short, cookies are intended to be stored in client side while sessions are stored in server-side (unless you're using cookie based session).
Users can clear http cookies from their browsers but they can't do anything about the sessions on your server. Clearing sessions is up you and your settings. There are some django settings you can use to determine their age like SESSION_COOKIE_AGE. For http cookies it's possible to set attributes like max_age, expires.
Choosing which one to use depends on your requirements; are you going to store sensitive data, is permanence important etc.
References:
Django sessions
Django request-response methods including set_cookie
Wikipedia HTTP cookies

Related

Avoid updating session cookie expire time on request to django

I'm trying to ping Django from a javascript frontend to find out when a user's session will expire. I'm doing this so I can proactively notify a user when their session has expired.
Unfortunately, the session expire time is updated because I'm hitting the Django app. I've tried reading the session cookie from javascript, but it is not accessible (nor recommended to be accessible) from javascript.
How can I ping my Django app from javascript to get when the session will end?
What about passing the number of seconds until session will expire directly to your template/javascript? For example, you can get it using this method in your view function and pass it further.

Django delete all cookies for all users

I have the django view to set the value in cookies 'no_show_dialog' when a user clicks 'Don't remind me anymore' in the modal dialog.
Now i changed that dialog completely and want to reset that cookie for all users, so they will have to see it again at least once.
I know there is a way to delete the cookie in a view for a particular user:
response.delete_cookie('no_show_dialog')
But how to loop over all users and remove that cookie once?
You can't do that. Cookies are stored on the client; the only time you have access to them is when the particular browser makes a request and receives the response.
The best thing to do here is to simply use a different name for the cookie from now on. This will ensure that no users will have it set initially. Alternatively you might consider using the session for future settings.
As Daniel said you cannot delete all cookies in response as they are stored on client side.
In Django you create a response object for a particular request object in your views. Which means that you can only delete a cookie for that particular request and not for all the requests that was served by your Django server.
What you can do here is set expiry time for a cookie by using max_age as keyword argument in set_cookie method For Example :
response = HttpResponse('your response')
response.set_cookie('user_id', user_id, max_age=30)
return response
This will expire the cookie after the specified time for every client.

Django session expires at browser close OR after time

The Django documentation states:
You can control whether the session framework uses browser-length
sessions vs. persistent sessions with the
SESSION_EXPIRE_AT_BROWSER_CLOSE setting.
If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use
browser-length cookies -- cookies that expire as soon as the user
closes his or her browser. Use this if you want people to have to log
in every time they open a browser.
This setting is a global default and can be overwritten at a
per-session level by explicitly calling the set_expiry() method of
request.session as described above in using sessions in views.
So when I set SESSION_EXPIRE_AT_BROWSER_CLOSE to True in my settings file, this indeed is what it does. This is good because I want a user's session to expire upon browser close. However, I also want a user's session to expire after, say, 15 minutes of inactivity. If I use set_expiry() mentioned above, the SESSION_EXPIRE_AT_BROWSER_CLOSE is overridden so if a user closes the browser and then re-opens the browser before the expiration, the session is still valid. Not what I want.
In addition, the documentation for set_expiry() says the sessions expires after the set amount of time of inactivity. That's actually not true. It expires no matter what, whether my user is clicking around on the site or not.
So to summarize, what I want to do is:
Have my sessions configured that if the user closes the browser, the session automatically expires.
Set a session expiration length that is updated with activity, i.e. if a user does something else on the site, the expiration is reset.
Thoughts/suggestions?
As Jiaaro suggested in this answer you can use SESSION_EXPIRE_AT_BROWSER_CLOSE and set a timestamp on session at each request and add a custom Middleware to handle the inactivity.
From docs https://docs.djangoproject.com/en/1.8/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions
Some browsers (Chrome, for example) provide settings that allow users to continue browsing sessions after closing and re-opening the browser. In some cases, this can interfere with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting and prevent sessions from expiring on browser close. Please be aware of this while testing Django applications which have the SESSION_EXPIRE_AT_BROWSER_CLOSE setting enabled.
Sessions expire when the user closes the browser:
This requirement implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.
Reference
Sessions expire after a period of inactivity:
SESSION_COOKIE_AGE is the age of session cookies, in seconds.
Default: 1209600 (2 weeks, in seconds)
Reference
You should set these option on your setting/__init__.py
Search engine cache make sure then the session will be closed when TOGETHER with SESSION_EXPIRE_AT_BROWSER_CLOSE = TRUE
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False, which means session cookies will be stored in users’ browsers for as long as SESSION_COOKIE_AGE. Use this if you don’t want people to have to log in every time they open a browser.
If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django will use browser-length cookies – cookies that expire as soon as the user closes their browser. Use this if you want people to have to log in every time they open a browser.

Working with Sessions and Cookies

I have this one question in mind that in login sessions does client have to maintain anything so that server uniquely identify client and in multiple client requests response to correct client. I don't understand this sessions and cookies. I asked many about this some say that its server job to maintain sessions and client just send normal request.
Yes, the client must keep track of something, called a session ID. Most commonly, it is a cookie. However, a less used approach is to rewrite all links to pass the session ID in the URL.
Example ID names are ASP.NET_SessionId and PHPSESSID.
Matthew's answer is correct.
It is the server's job to keep track of login sessions, and it's the client web browser's job to keep track of cookies. When you provide username & password on a site, a cookie is provided by the web server to your browser, which will automatically be provided along with subsequent requests to the web server. This cookie uniquely identifies a session which belongs to a particular user on the site (even the "guest" user). So, the server keeps track of all client sessions, and each client remembers its session cookie & provides it along with all its requests. It's a simple scheme. Using Firebug for example, you can see what the web requests look like when you log into a site. You might find that interesting to look at.
It is the server which will maintain the sessions. And it is the server responsibilty to allow session tracking happen. Clients need not bother about sending any information explicitly. As Cliens also sends Cookies saved on the client along with every request, server might use Cookies for sesssion tracking.
Note: Cookies are just one of the way to implement Session Tracking. It is also the best way
So server Cookies as one of the ways to handle session tracking.
It can also be done in other ways:
URL rewriting - the application/server should append the session id in all URL's/Links. When those are invoked from the client the session comes to the server along with the URL.
Hidden Form Fields - The forms may contain hidden input type with session id as field value. When the form is posted, the session id comes along with the form data.

What is the difference between a cookie and a session in django?

I think they are same thing but my boss say that is not right. Can someone explain the difference?
A cookie is something that sits on the client's browser and is merely a reference to a Session which is, by default, stored in your database.
The cookie stores a random ID and doesn't store any data itself. The session uses the value in the cookie to determine which Session from the database belongs to the current browser.
This is very different from directly writing information on the cookie.
Example:
httpresponse.set_cookie('logged_in_status', 'True')
# terrible idea: this cookie data is editable and lives on your client's computer
request.session['logged_in_status'] = True
# good idea: this data is not accessible from outside. It's in your database.
A cookie is not a Django, or Python specific technology. A cookie is a way of storing a small bit of state in your client's browser. It's used to supplement (or hack around, depending on your point of view) HTTP, which is a stateless protocol. There are all sorts of limitations here, other domains cant read your cookies, you can only store a a few k of data (just how much depends on the browser!), etc, etc.
A cookie can be used to store a session key. A session is a collection of user state that's stored server side. The session key gets passed back to the server, which allows you to look up that session's state. Most web frameworks (not just Django) will have some sort of session concept built in. This lets you add server-side state to an HTTP conversation.
To complement 'Yuji 'Tomita' Tomita's answer'
with cookies You can set any information on client browser
not just id (session id),
cookies are limited (size limited to kb), less secure and less flexible compared to sessions.
django sessions are based on cookies, django uses a cookie to save session id on client
sessions are not limited to data size (because they are saved on db of server), more secure and more flexible.