Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle Exceptions raised by django-social-auth?

In django-social-auth, there are a few instances where a back-end will raise a ValueError (such as when a user cancels a login request or if a user tries to associate with an account that's already been associated with another User). If a User runs into one of these scenarios, they'll be presented with a 500 error on your site.

So, what's the best way to catch these? I'd prefer to be able to display a useful message (via the messages framework) when this happens, but I'm at a loss as to the best way to do this.

I'm thinking about writing my own view (in a separate app) that just wraps social_auth's associate_complete view, but this seems clunky... Any ideas?

I could fork django-social-auth and customize this behavior, but I'd prefer not to maintain a separate fork - especially since I can't assume everone would want to handle these Exceptions in the same manner.

like image 771
Brad Montgomery Avatar asked Jun 24 '11 04:06

Brad Montgomery


People also ask

What is Django Social Auth?

Django Social Auth is an easy way to setup social authentication/authorization. mechanism for Django projects. Crafted using base code from django-twitter-oauth_ and django-openid-auth_, it implements a common interface to define new authentication providers from. third parties.


3 Answers

Rather old question but worth mention that recent version of DSA supports a custom exception processor where you can do whatever you want with the exception message. The default version stores them in the messages app.

Also the exceptions are differentiated now instead of the not-useful ValueError used. Check the docs http://django-social-auth.readthedocs.org/en/latest/configuration.html.

Update (13/08/2013):

Since I've posted the above things have changed, now DSA has an exception middleware that when enabled stores the exception message in the jango builtin messages app. It's preferable to subclass the middleware and add the custom behavior to it. Check the doc at http://django-social-auth.readthedocs.org/en/latest/configuration.html#exceptions-middleware

Sample middleware:

# -*- coding: utf-8 -*-
from social_auth.middleware import SocialAuthExceptionMiddleware
from social_auth.exceptions import AuthFailed
from django.contrib import messages

class CustomSocialAuthExceptionMiddleware( SocialAuthExceptionMiddleware):

    def get_message(self, request, exception):
        msg = None
        if (isinstance(exception, AuthFailed) and 
            exception.message == u"User not allowed"):
            msg =   u"Not in whitelist" 
        else:
            msg =   u"Some other problem"    
        messages.add_message(request, messages.ERROR, msg)     
like image 121
omab Avatar answered Oct 11 '22 20:10

omab


I've ecountered the same problem and it seems, that creating wrapper view is the best way to handle this situation, at this point, atleast. Here is how I had mine done:

def social_auth_login(request, backend):
    """
        This view is a wrapper to social_auths auth
        It is required, because social_auth just throws ValueError and gets user to 500 error
        after every unexpected action. This view handles exceptions in human friendly way.
        See https://convore.com/django-social-auth/best-way-to-handle-exceptions/
    """
    from social_auth.views import auth

    try:
        # if everything is ok, then original view gets returned, no problem
        return auth(request, backend)
    except ValueError, error:
        # in case of errors, let's show a special page that will explain what happened
        return render_to_response('users/login_error.html',
                                  locals(),
                                  context_instance=RequestContext(request))

You will have to setup url for it:

urlpatterns = patterns('',
    # ...
    url(r'^social_auth_login/([a-z]+)$',  social_auth_login, name='users-social-auth-login'), 
)

And then use it as before in template:

<a href="{% url 'users-social-auth-login' "google" %}">Log in with Google</a>

Hope this helps, even aftern two months after question was asked :)

like image 13
Silver Light Avatar answered Oct 11 '22 19:10

Silver Light


You need add social auth middleware:

MIDDLEWARE_CLASSES += ('social_auth.middleware.SocialAuthExceptionMiddleware',)

If any error occurs user will be redirected to erorr url(LOGIN_ERROR_URL from settings).

For detailed explanation please see documentation: http://django-social-auth.readthedocs.org/en/latest/configuration.html#exceptions-middleware

like image 6
Yevgeniy Shchemelev Avatar answered Oct 11 '22 21:10

Yevgeniy Shchemelev