Redirect after login_required loses POST parameters - django

I have a view that looks something like this simplified example:
#decorators.login_required()
def add_data(request):
some_value = request.POST['some_value']
# do stuff.
If a user is authenticated already, this completes successfully. If the user is not authenticated, this redirects to the login page. After the login page, the POST request is sent back to my add_data view is missing some_value and all other POST data.
Is this expected? Is there a way to access the POST data?
I am using the default django.contrib.auth.views.login. I have a custom login.html.

Is this expected?
Yes.
Is there a way to access the POST data?
Probably not, the anonymous user and logged in user will have separate sessions so that won't work.
You might be able to some how store the data in a GET variable and pass it to the login form, and then inspect that.
I'd suggest its just a case where the user has messed up, and they should check they are logged in before submitting things.

Related

How to get POST parameters in a Django view protected by #login_required?

Django's login_required decorator requires a login before proceeding to any functionality in a view function. If a user is not logged in, they will be redirected through a login screen.
If the HTTP request is a GET, Django sometimes puts the GET destination in a parameter ("next"). Or, Django also has a LOGIN_REDIRECT_URL setting that is a URL a user is forwarded to after login.
If the HTTP request is a POST, that POST data is lost during the login process.
What is the best way to preserve the original URL and POST data for the original POST request, and re-post that data after the user is logged in?
I imagine putting something in a session, but I'd have to intercept the POST data and URL on the way through login_required. The best practice is not obvious to me.

Django - Prevent a User from Accessing a Page when He/She Typed the URL

I have a page in Django that I don't want to be accessed by anyone except when they clicked the specific link that I made for that page.
I'm aware about #login_required but the problem is I want the page to be restricted to EVERYONE.
I haven't tried any code yet since I absolutely have no idea how to do it. Even google did not give me answer. Please help
I have the same problem a few months back and way I solved it by making a POST request.
Whenever any user clicks on the link present on-page, I make a POST request at the Django application with some verification token sent in the POST request body.
You can generate any simple token mechanism and check for token validity in Django view and if success allows users to access that page.
The most common way to achieve this is to use randomized links.
In pseudo code
Page 1
<a href="/router/some-random-string">
# view serves '/secret-page'
class SecretView:
def _get(request):
# display real page here
def get(request):
return HttpNotFound()
# view serves '/router/<hash:str>'
class AccessorView(SecretView):
def get(request):
# get and validate hash
# if valid, display secret page
return super()._get(request)

Django redirect shortcut changes request.user

I have an application where we have sub-classed the Django 'User' object into, say, 'AppAccount' object which has additional attributes. Now I have a view where I do the following:
appAccountObject.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, appAccountObject)
redirect(someOtherView)
Now according to pdb, request.user is an instance of AppAccount right after the login() call, but request.user is a Django User instance in the first line of someOtherView.
Why is the redirect call changing the User object back to the normal Django User? How can I avoid this?
Also, is the above code correct? Should adding the backend attribute be okay to bypass a call to authenticate? If not, what should the correct way of doing this be: I want to login a user automatically, without their credentials and then redirect to another view which is wrapped by a #login_required decorator.
Thanks.
A redirect causes a whole new request from the user's browser, hence the user object has to be fetched from the database again based on the session cookie and assigned to request.user. This happens in the authentication middleware. Unless you've written your own version of this, it's always going to use the default user class.
This is just one of the reasons why it's a bad idea to subclass User. Instead, extend it with a UserProfile class with a OneToOne relation to User.

Django: How to destroy user session after a password reset/change?

i've recently implemented a simple change password view in my django project. The thing is that the old session should be destroyed for security reasons. What's the best way of doing this without asking the user to log in again.
I think i could just logout/login him/her, something like this:
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
#login_required
def change_password(request):
# My stuff
request.user.set_password(new_password)
request.user.save()
# I need this:
logout(request)
login(request,request.user)
But i think this is not the best idea. What do you think?
Is there another way to do this?
Am I missing something? (I mean, is this secure)
Take a look at this app https://github.com/atugushev/django-password-session.
This package makes invalidated all sessions (except a current session) after change a password.
Also this feature finally was implemented in Django 1.7. See: https://docs.djangoproject.com/en/dev/topics/auth/default/#session-invalidation-on-password-change
I just found out that this is now a built-in feature of Django, and has been since 1.7:
https://docs.djangoproject.com/en/1.7/topics/auth/default/#session-invalidation-on-password-change
Essentially, all sessions now include a hash of the users' password, so if the user ever changes their password, all their existing sessions are automatically invalidated.
So, the short answer to your question is: upgrade django.
One possibly undesirable side effect of this change is that, by default, a user ends up having to log in again as soon as they change their password. So you probably actually want the current user session to stay logged in. See the docs already linked, Django's built-in views for password change do that for you default, or you can manually call a function called update_session_auth_hash
django clears the session on logout so you will be fine:
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.logout
When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same Web browser to log in and have access to the previous user's session data.
I don't understand whats are these security reasons that forces to reset session. But, the way is:
#login_required
def change_password(request):
request.user.set_password(new_password)
request.user.save()
username = request.user.username
logout(request)
user = authenticate(username=username, password=new_password) #<-- here!!
if user is not None:
login(request,user)
else:
#raise your exception
you should authenticate before login. Quoting doc:
Calling authenticate() first When you're manually logging a user in,
you must call authenticate() before you call login(). authenticate()
sets an attribute on the User noting which authentication backend
successfully authenticated that user (see the backends documentation
for details), and this information is needed later during the login
process.

Django: any way to avoid querying for request.user on every request?

For my website pretty much every page has a header bar displaying "Welcome, ABC" where "ABC" is the username. That means request.user will be called for every single request resulting in database hits over and over again.
But once a user is logged in, I should be able to store his user instance in his cookie and encrypt it. That way I can avoid hitting the database repeatedly and just retrieve request.user from the cookie instead.
How would you modify Django to do this? Is there any Django plugins that does what I need?
Thanks
You want to use the session middleware, and you'll want to read the documentation. The session middleware supports multiple session engines. Ideally you'd use memcached or redis, but you could write your own session engine to store all the data in the user's cookie. Once you enable the middleware, it's available as part of the request object. You interact with request.session, which acts like a dict, making it easy to use. Here are a couple of examples from the docs:
This simplistic view sets a has_commented variable to True after a user posts a comment. It doesn’t let a user post a comment more than once:
def post_comment(request, new_comment):
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
This simplistic view logs in a "member" of the site:
def login(request):
m = Member.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
This smells of over-optimisation. Getting a user from the db is a single hit per request, or possibly two if you use a Profile model as well. If your site is such that an extra two queries makes a big difference to performance, you may have bigger problems.
The user is attached to the request object using the Authentication Middleware provided by django (django.contrib.auth.middleware). It users a function the get_user function in django.contrib.auth.init to get the user from the backend you are using. You can easily change this function to look for the user in another location (e.g. cookie).
When a user is logged in, django puts the userid in the session (request.session[SESSION_KEY]=user.id). When a user logs off, it erases the user's id from the session. You can override these login and logoff functions to also store a user object in the browsers cookie / erase user object from cookie in the browser. Both of these functions are also in django.contrib.auth.init
See here for settting cookies: Django Cookies, how can I set them?
Once you have proper caching the number of database hits should be reduced significantly - then again I'm not really and expert on caching. I think it would be a bad idea to modify request.user to solve your problem. I think a better solution would be to create some utility, method or custom template tag that attempts to load your require user data from the cookie, and return the result. If the user data is not found in the cookie, then a call to request.user should be made, save the data to the cookie, and then return the result. You could possibly use a post_save signal to check for changes to the user data, so that you can make update to the cookie as required.