Changing django-allauth render_authentication_error behavior - python

I'm a newcomer to the python/Django universe and just started a huge project I'm pretty excited about. I need to have my users login through Facebook and my app has a really specific user flow. I've set up django-allauth and everything works as I needed. I've overriden LOGIN_REDIRECT_URL so that my users land on the page I want when they log in.
BUT. When the user opens Facebook login dialog box and then closes it without logging in, the authentication_error.html template gets rendered by allauth.socialaccount.helpers.render_authentication_error, and this is not the behaviour I want. I want the user to simply be redirected to the login page.
Yes, I know I could simply override the template by putting it in my TEMPLATE_DIRS, but then the url wouldn't be the same.
I've come to the conclusion I needed a middleware to intercept the response to the http request.
from django.shortcuts import redirect
class Middleware():
"""
A middleware to override allauth user flow
"""
def __init__(self):
self.url_to_check = "/accounts/facebook/login/token/"
def process_response(self, request, response):
"""
In case of failed faceboook login
"""
if request.path == self.url_to_check and\
not request.user.is_authenticated():
return redirect('/')
return response
But I'm not sure about the efficiency of my solution nor the pythonesquitude (I juste came up with that word) of it. Is there anything else I could do to change that default django-allauth behavior without using a middleware or a signal?
Thanks!

Yes, I know I could simply override the template by putting it in my TEMPLATE_DIRS, but then the url wouldn't be the same.
Overriding a template won't change the URL. In your overridden template, you could do a client-side redirect to whatever URL you prefer.

I decided to use a middleware and redirect to home url in case a GET request is made on a URL of the form ^/accounts/.*$
from django.shortcuts import redirect
import re
class AllauthOverrideMiddleware():
"""
A middleware to implement a custom user flow
"""
def __init__(self):
# allauth urls
self.url_social = re.compile("^/accounts/.*$")
def process_request(self, request):
# WE CAN ONLY POST TO ALLAUTH URLS
if request.method == "GET" and\
self.url_social.match(request.path):
return redirect("/")

Related

How to redirect url from middleware in Django?

How to redirect url from middleware?
Infinite loop problem.
I intend to redirect the user to a client registration url if the registration has not yet been completed.
def check_user_active(get_response):
def middleware(request):
response = get_response(request)
try:
print(Cliente.objects.get(usuario_id=request.user.id))
except Cliente.DoesNotExist:
return redirect('confirm')
return response
return middleware
Every request to server goes through Middleware. Hence, when you are going to confirm page, the request goes through middleware again. So its better put some condition here so that it ignores confirm url. You can try like this:
def check_user_active(get_response):
def middleware(request):
response = get_response(request)
if not request.path == "confirm":
try:
print(Cliente.objects.get(usuario_id=request.user.id))
except Cliente.DoesNotExist:
return redirect('confirm')
return response
return middleware
You should be using a login_required like decorator see Django authentication system for more detail.
Example:
from django.contrib.auth.decorators import login_required
#login_required(login_url="/your/login/view/url/")
def my_view(request):
...
Avoid using middlewares for any kind of redirection always you can, according to the docs
Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.
In other words, middlewares are there for processing request and responses, if you redirect to any view, you will (potentially) recursively trigger your middleware.
And, on the other hand ...
In the future, you might want to add a view that can be visited by anonymous users, this middleware will be a problem ...

Redirecting Django built-in login View to a URL taking user's pk as argument

I am trying to redirect to a URL taking user's pk as argument after successful log-in using Django's built-in login view.
Instead of dynamic {{ next }} variable in my login.html I have a generic landing view of logged-in users;
<input type="submit" value="login" />
<input type="hidden" name="next" value="{% url 'userredirect' %}" />
In my urls.py I have;
url(r'^users/', views.users, name='userredirect'),
url(r'^(?P<pk>\d+)/', UserHome.as_view(), name='userhome'),
and in my views.py I have
#login_required
def users(request):
url = reverse('userhome', kwargs={'pk':request.user.id})
return HttpResponseRedirect(url)
What I am doing here is redirect to a detail view that I have named UserHome on the user model after successful login using 2 redirects as I do not know of a way to redirect to UserHome directly (it takes user's pk as argument). It works and I indeed get redirected to the user's homepage when checking via the browser.
Reference;
The "next" parameter, redirect, django.contrib.auth.login
But when running the below test
def test_page_redirects_to_user_home_on_login(self):
"""
Test to assure that the login page redirects to the user's
home page
"""
username = "someusername"
password = "somepassword"
user = User.objects.create_user(username=username,
password=password)
user.save()
response = self.client.post(reverse("userlogin"),
{"username":username,
"password":password},
follow=True)
assert response.path == self.client.get(reverse("userhome",
kwargs={"pk":user.id}
)
)
I get the below failure
AttributeError: 'HttpResponseNotFound' object has no attribute 'path'
It seems the test client gets no page. Would it be that I am using the userredirect view simply for redirecting and the client do not go ahead and get the UserHome class view to its context.
I'm a newbie to Django/Python. Someone please sort this out for me :).
I look forward either to a way where I can redirect directly from the template for login view to UserHome or a way to rewrite my test.
Hard to say without much more insight in your project. Here are a few possibilities and such.
Response has no path
response indeed has no path, you probably wanted this:
assert response.wsgi_request.path == reverse("userhome", kwargs={"pk":user.id})
Include next in your test
You're simulating data from the login form, but you're omitting the next field.
Add it to the POSTed data:
{"username":username,
"password":password,
"next": '/users/',}
Take a look what's in the response
It might help to see what's in the response in your test. For example:
print(response.redirect_chain)
Perhaps you're not even reaching the login page?
Are you missing LOGIN_URL in your settings.py?
LOGIN_URL = '/login/'
Without it, you'll be redirected to '/accounts/login/', which might be the 404 you're seeing.
Finaly - why? :)
Perhaps you have some special use case, but I'd usually read user's id (a.k.a. pk) from request.user. That way I (for example) can't access example.com/<your_id> and access your homepage. Of course, that might be just what you intend. In that case I'd still have a separate URL for current user, it will probably pay off later. Something like this:
...
url(r'^/', UserHome.as_view(), name='userhome'),
url(r'^(?P<pk>\d+)/', UserHome.as_view(), name='userhome'),
...)
class UserHome(DetailView): # also protect with some LoginRequiredMixin
model = User
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
id = self.kwargs.get('pk', self.request.user.id)
return queryset.filter(id=id).get()
First things first: The error you get is because the line
response = self.client.post(reverse("userlogin"),
{"username":username,
"password":password},
follow=True)
raises a 404 error, hence resonse is a HttpResponseNotFound.
Before testing anything else is it a good practice to first test that your request was successful. Something along the line of:
self.assertEqual(response.status_code, 200)
Also, you are hard-coding url's which goes against DRY and is often the source for trouble (maybe it is the case here).
It would be better to name all your urls:
url(r'^users/', views.users, name='user_redirect'),
and then use this in your template
<input type="hidden" name="next" value="{% url 'user_redirect' %}" />
and this in your view
from django.core.urlresolvers import reverse
#login_required
def users(request):
url = reverse('userhome', kwargs={'pk': request.user.id})
return HttpResponseRedirect(url)
And finally, you are taking an unnecessary step with the redirect. Assuming UserHome is a DetailView on User, you could have this code:
##urls.py
url(r'^users/', UserHome.as_view(), name='userhome')
##views.py
from django.views.generic import DetailView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
class UserHome(DetailView):
model = User
def get_object(self, queryset=None):
return self.request.user
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(UserHome, self).disatch(*args, **kwargs)
This would also ensure that no user accesses another user's "userhome".
Doing all this should help you find what went wrong with your code. Good luck!

Django REST Framework CSRF Failed: CSRF cookie not set

I am using the django rest framework to perform API calls via IOS
and I get the following error
"CSRF Failed: CSRF cookie not set."
Here's my django API code:
class LoginView(APIView):
"""
List all snippets, or create a new snippet.
"""
#csrf_exempt
def get(self, request, format=None):
startups = Startup.objects.all()
serializer = StartupSerializer(startups, many=True)
return Response(serializer.data)
#csrf_exempt
def post(self, request, format=None):
profile = request.POST
....
What can I do?
If anyone is still following this question, the direct answer is that you need to use the decorator on the view method itself. The get and post methods defined on the APIView class just tell DRF how the actual view should behave, but the view method that the django router expects is not actually instantiated until you call LoginView.as_view().
Thus, the solution is to add the csrf_exempt decorator to urls.py. It might look as follows:
#file: urls.py
from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
import views
urlpatterns = patterns('',
url('^login/$', csrf_exempt(views.LoginView.as_view())),
...
)
However, as Mark points out above, csrf protection is important to prevent your sessions from being hijacked. I haven't worked with iOS myself, but I would look into using django's cookie-based csrf tokens. You can use the ensure_csrf_cookie decorator to make django send a csrftoken cookie with a response, and your POST requests will validate as long as you include that token as an X-CSRFToken header.
I've had the same issue. My problem was that I forgot to put .as_view() in urls.py on MyAPIView. So it have to be like:
url(r'$', GetLikesAPI.as_view(), name='list')
not:
url(r'$', GetLikesAPI, name='list')
The problem you encounter here is that django for processing your view is using whatever as_view() method will return, not directly method get() or post().
Therefore you should decorate your class-based view in one of following ways:
In urls.py
urlpatterns = patterns('',
url('^login/$', csrf_exempt(views.LoginView.as_view())),
...
)
or on dispatch() method (pre django 1.9)
from django.utils.decorators import method_decorator
class LoginView(APIView):
#method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
...
or on class view itself (from django 1.9)
from django.utils.decorators import method_decorator
#method_decorator(csrf_exempt, name='dispatch')
class LoginView(APIView):
...
For GETs, you shouldn't be modifying data, so a CSRF isn't required.
If you are modifying data with a POST, then you SHOULD have a CSRF if you are using session based authentication. Otherwise, you're opening up a security hole. Even though you think your Django server is going to be servicing iPhone apps, there's nothing to stop someone with your app from sniffing the packets on the traffic to your server, and then reverse engineering access to the server with other kinds of web clients. For this reason, Django Rest Framework requires a CSRF in some cases. This is mentioned in the Django rest framework documentation.
The path around this requirement for POSTs is to not use session authentication. For example, you could use BasicAuthentication over HTTPS. With this authentication mechanism, you should use HTTPS to prevent credentials from being passed in the clear with every request.
This is an old question but something we ran into recently.
DRF disables CSRF by default, unless using session authentication. By default NSURLconnection is set up to handle cookies. You need to explicitly tell the iOS app to not use cookies. Then you can keep using session auth if needed and not have to csrf exempt your views.
urlpatterns = patterns('',
url('^login/$', csrf_exempt(views.LoginView.as_view())),
...
)
Guys. I had the same error and spent a lot of time just for finding that:
1) I had another router with 'login' and there i missed '$'. I mean sometimes you can forget something in routing and get this error.
In my case it happend because I sent put request to url='http://example.com/list/5' without slash at the end. When I changed url to url='http://example.com/list/5/' all started to work.

How to check every request in pyramid for redirect?

I want to redirect users to a change password page when their password expired. I already setup a RequestFactory that takes the user. Where do I put the redirecting part in Pyramid?
I'm not sure to understand your question, but the usual way to redirect in Pyramid is to return an HTTPFound instance in your view function. I think you could also just raise it since it's an exception.
from pyramid.httpexceptions import HTTPFound
def my_view(request):
return HTTPFound('/new/location/to/redirect')
A good practice is to use route_url to build the url you are redirecting to.

How can I redirect after POST in Pyramid?

I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.
For example:
User loads the page website.com/post
Form POSTs the data to website.com/post-save
User gets redirected back to website.com/post
Pyramid is giving me some troubles doing this.
Here's my slimmed down views.py
def _get_link_form(post_data):
""" Returns the initialised form object """
return LinkForm(post_data)
def home_page(request):
form = _get_link_form(request.POST)
return {'form' : form}
def save_post(request):
""" form data is submitted here """"
form = _get_link_form(request.POST)
if not form.validate():
return home_page(request, form)
This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?
Your problem is most easily solved by simply POSTing to the same URL that your form is shown at, and simply redirecting the user away from the page when the POST is successful. That way until the form is successfully submitted you do not change URLs.
If you're just dying to POST to a different URL, then you need to save the data using sessions, since you're obviously handling the form data between requests.
Typically if you want to be able to handle errors in your forms you would use a session and flash messages. To do this you simply add a location for flash messages to appear in your base template and setup session support using something like pyramid_beaker.
Assuming your home page is setup at the 'home' named-route:
from pyramid.httpexceptions import HTTPFound
def myview(request):
user = '<default user field value>'
if 'submit' in request.POST:
user = request.POST.get('user')
# validate your form data
if <form validates successfully>:
request.session.flash('Form was submitted successfully.')
url = request.route_url('home')
return HTTPFound(location=url)
return {
# globals for rendering your form
'user': user,
}
Notice how if the form fails to validate you use the same code you did to render the form originally, and only if it is successful do you redirect. This format can also handle populating the form with the values used in the submission, and default values.
You can loop through the flash messages in your template of choice using request.session.peek_flash() and request.session.pop_flash().
route_url supports mutating the query string on the generated url as well, if you want to flag your home page view to check the session data.
You can obviously just pass everything in the query string back to the home page, but that's a pretty big security vulnerability that sessions can help protect against.
The Pyramid documentation has a particularly on-point section with the following example:
from pyramid.httpexceptions import HTTPFound
def myview(request):
return HTTPFound(location='http://example.com')
I do this like so:
from pyramid.httpexceptions import HTTPCreated
response = HTTPCreated()
response.location = self.request.resource_url( newResource )
return response
This sends the HTTP Created code , 201
The Pyramid documentation has content about Redirect, you can see more information in below link :
Pyramid documentation
import pyramid.httpexceptions as exc
raise exc.HTTPFound(request.route_url("section1")) # Redirect
Edited:
Actually you can do that on client side with Javascript, first you should send particular response to client side(either with flashes some data or return Response object):
window.location = '{{ request.route_path("route_name") }}';
Assuming your homepage is the default view of your pyramid web app, you can do:
def _get_link_form(post_data):
""" Returns the initialised form object """
return LinkForm(post_data)
def home_page(request):
form = _get_link_form(request.POST)
return {'form' : form}
def save_post(request):
form = _get_link_form(request.POST)
if not form.validate():
from pyramid.httpexceptions import HTTPFound
return HTTPFound(location=request.application_url)
Basically you need to know how the home_page view was "added" to your Configurator. If your homepage actually lives at /few/levels/deep/homepage then a redirect might look like this:
return HTTPFound(location=request.application_url + '/few/levels/deep/homepage')
A clean way is using the "overload" provided by pyramid for different request types, por example, you can decorate your methods this way:
#action(request_method='GET',
renderer='mypackage:/templates/save.mako',
name='save')
def save(request):
''' Fill the template with default values or leave it blank'''
return {}
#action(request_method='POST',
renderer='mypackage:/templates/save.mako',
name='save')
def save_post(request):
""" form data is submitted here """"
# process form
In the HTML, you must call the action form, like
<form method="POST" id="tform" action="${request.route_url('home', action='save')}">
This way, one method is processed when the method POST is used, and the other when the GET is used. The same name, but two implementations.

Categories

Resources