How can I do this
request.session['key'] = 'value'
for the user which user_id is 47?
Keep in mind that I'm not currently logged in with that user, I want to do it in shell.
See the section of the Session docs entitled "Using sessions out of views".
The problem though is that Django doesn't store the user with the session (by design, for security purposes). So the only way to retrieve a session is through it's key. That key is stored with the user's client and passed to the server to associate the session with the logged in user. In other words, you're going to have a hard time determining which session belongs to which user.
More to the point, the session data is actually encrypted in the database as well, so there's not even any way to query directly for the user id stored in it. The following will work, but you'll have to query each session one by one to get the right user. Depending on how many sessions your database currently has, this could be extremely expensive. Mark as USE AT YOUR OWN RISK
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore
for session in Session.objects.all():
data = SessionStore().decode(session.session_data)
if data.get('_auth_user_id') == user_id_you_want:
user_session = SessionStore(session_key=session.session_key)
# you can modify the session data here like normal, then:
user_session.save()
The answer depends entirely on the session storage/engine you're using.
So, the generic answer would be: Wherever the session is being stored, modify it there.
For the database backend: UPDATE django_session SET session_data=[whatever] WHERE session_key=[whatever];
You'll also need the session key and the AES key stored in the client browser.
Alternatively, send them to a controller that updates the session.
Related
After successful authentication the user I am setting following -
self.set_secure_cookie('user', str(user.id), 1)
self.set_secure_cookie('expires_days', 1)
self.set_secure_cookie('max_age_days', 1)
Now the requirement is to logout all users on a specific action. For this I am trying -
self.clear_all_cookies()
but this is only logging out the current user. Not other users logged-in from other machines or browsers.
I am using tornado 4.3 and Python 2.7
Any way I this can be acheived?
You can't delete the cookies of all "connected" users with in one go as each request is handled separately, but you can try invalidating them so they can be deleted on their next request.
A simple solution would be to store a cookies_valid_from timestamp in your Application and on user login set a created_on timestamp cookie for the user. Your get_current_user() function could look like this:
def get_current_user(self):
if self.get_secure_cookie("created_on") < self.application.cookies_valid_from:
self.clear_all_cookies()
return None
return self.get_secure_cookie("user")
The specific "log out all users" action you mention can simply update the cookies_valid_from timestamp to the current time.
To invalidate absolutely everything, you can simply change your cookie secret. All existing cookies will be ignored and you can begin issuing new ones. But if you need something more nuanced than that, you'll have to design it in to your authentication protocol. For example, don't just store the user ID in the cookie, store a session ID and keep track of the currently-valid session IDs in a database or cache. Then you can invalidate user sessions by deleting their IDs from the database.
How to get django user session objects from user id or email?
I am stuck with a problem for a particular user, he gets logged out from the system very frequently. I need to get the list of session objects for a particular user.
Session object is accessible by session_key, which is random string. It's generated on server side and stored in client side in Cookie. So it's impossible to identify user by session.
I can't seem to find the the signal that tie with a 'session created' .
I'm aware of auth signals , but what i want is to populate a session variable for anonymous users.
What am i missing ?
Thanks in Advance
To store a session variable for anonymous users, you can do something as simple as request.session['something'] = True (or whatever value you want) in the appropriate view. And if you're trying to see if you've seen an anonymous user before, you can just test for the existence of the 'something' key.
Under the hood, django handles cookie setting and creates a session for an anonymous user if you modify the session variable. If the anonymous user already has a session, it simply records the modified state.
Take a look at the session docs: https://docs.djangoproject.com/en/dev/topics/http/sessions/ for more details. It's pretty sophisticated.
Finally, don't forget to clean expired sessions periodically with ./manage.py clearsessions if sessions are stored in a persistent store.
Is it possible to create Flask Sessions without Login Fields, For Example user can enter only Email address in User Name Field, which will create Session with certain expiration time, till the session is active, User2 cannot create session with same name.
Any help is highly appreciated.
At first flask by default do not store session on server - only safe cookies.
If you want use email as id (user.get_id() method) you can't. But you can create special cache (dict or etc) on server with active sessions and use unique keys as id and do not login users with exist email.
When a new user is created, I want to retain some of the information in their session
e.g. things a user has stored in their session I want to use once they have registered (or logged in).
I would use either a post_save signal on the user model (or an auth login signal), but it appears that the signals don't put the request, or session into the signal sent. It also seems I can't easily get the session from just the user.
I'm using Django 1.4
Edit: let me give an example.
The problem boils down to this - I may want to retain information for a user's activities before they login, but where do I store this information before they login? A good place would be a session (or I could link the data held in a db to the session, using the session a little like a makeshift user).
In any case, until they login, I can simply use their session like a user credential, and store information that persists so long as their cookie does (how else can could I reliably track an anonymous user?).
But once they register (or log-in), I want to move that information from the session, into the account properly. One good reason is that it would make sense to delete data from anonymous users periodically, whereas registered user's data would be persisted.
To do this I simply want access to the session (could be via the request) from a handler to the new-user signal, so I can make a one-off transfer from data in the session. But the new-user signal doesn't hold the session (or request).
If you're using django.contrib.sessions and django.contrib.auth for the job, the session data should be retained automatically after login.
Moreover, the user_logged_in signal is sent along with request actually.
Edit:
So use user_logged_in signal. It carries request. Pick some specific key to store unauthenticated user's data (e.g. "_anonymous_data"). If that key is set on request.session while handeling signal, simply rewrite data on request.user.get_profile() object, call save and del request.session["_anonymous_data"].
The code to retreive it could look something like:
if request.user.is_authenticated():
user_data = request.user.get_profile()
else:
user_data = requerst.session["_anonymous_data"]
It's only a scratch of course. You don't want to hardcode session keys or write such logic in views. If you need it application wide, embed it in some abstraction class which takes request in __init__.
you could try using sessions:
https://docs.djangoproject.com/en/dev/topics/http/sessions/?from=olddocs