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.
Related
I'm building a Django where the admin will create a user and then one mail will be sent to the user. In the mail, I'm also sending one token with the URL on clicking which the user will get verified by checking the correctness of the token.
But the problem is I'm storing the token in Django session and when I open the link on the same browser it works but on a different machine user is not getting verified as session data becomes unavailable.
Someone suggest me the best way to store the token.
I didn't want to use the database as it doesn't make sense.
Hey guys I am confused and was thinking about this problem for sometime now, I am storing the current user's username in the session storage, and I have another page in which I use the stored username for an api call, it can be any requests.
Eg. a post can be deleted by its author only, suppose, the url is api/<slug>/delete and in the frontend I have enabled the delete button only for the corresponding user, what if he edits the front end page and changes it to his username or what if I use the stored username to check that condition?
And if he sends a delete request successfully from the frontend, does the django server able to determine that the user in the current session is not the real owner and has tweaked it in the frontend?
Ps. This might be a foolish question, but I am a beginner and quite confused.
Thanks.
Naturally, we would need some code to answer your question.
Will the following delete some other user's data?
A user passes a username from the client to the server
SomeModel.objects.filter(username=username).delete()
Will the above delete the user data whose username is what has been passed from the client? Yes.
You need to always verify and validate data and permissions on the server, and also you should consider using CRUD operations on the current authenticated user (since you are working with sessions), so you don't have to send the current user' username from client, if they are logged in, that can be validated with their session.
I'd advise you to read a little more on Authentication, sessions, ect. authentication in Django
Also, I see you are using A RESTful API, so I would strongly recommend using DRF
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.
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.
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.