python-social-auth AuthCanceled exception
Asked Answered
C

7

31

I'm using python-social-auth in my Django application for authentication via Facebook. But when a user tries to login, they have been redirected to the Facebook app page, and they click on the "Cancel" button, the following exception appears:

ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/
Traceback (most recent call last):
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 45, in wrapper
    return func(request, backend, *args, **kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 21, in complete
    redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/actions.py", line 54, in do_complete
    *args, **kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/strategies/base.py", line 62, in complete
    return self.backend.auth_complete(*args, **kwargs)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 63, in auth_complete
    self.process_error(self.data)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 56, in process_error
    super(FacebookOAuth2, self).process_error(data)
  File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/oauth.py", line 312, in process_error
    raise AuthCanceled(self, data.get('error_description', ''))
AuthCanceled: Authentication process canceled

Is the any way to catch it Django?

Cormophyte answered 3/1, 2014 at 15:39 Comment(0)
K
21

you can create a middleware and catch any exceptions, exception list: https://github.com/omab/python-social-auth/blob/master/social/exceptions.py in this case your AuthCanceled Exception.

middleware.py



from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import HttpResponse
from social import exceptions as social_exceptions

class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
    def process_exception(self, request, exception):
        if hasattr(social_exceptions, 'AuthCanceled'):
            return HttpResponse("I'm the Pony %s" % exception)
        else:
            raise exception


settings.py



MIDDLEWARE_CLASSES = (
        .....
        'pat_to_middleware.SocialAuthExceptionMiddleware',
)


Klement answered 6/1, 2014 at 20:26 Comment(3)
hasattr(social_exceptions, 'AuthCanceled') returns true even if the exception is not AuthCanceled. It catches all other errors even 404.Kistner
Caution, this will not work if INSTALLED_APPS includes 'debug_toolbar' as it wraps the middleware and prevents the exception from percolating through the process_exception functionsLeicestershire
Yes, it's only an example.Unreal
G
46

python-social-auth is a newer, derived version of django-social-auth.

AlexYar's answer can be slightly modified to work with python-social-auth by modify settings.py with following changes:

  1. Add a middleware to handle the SocialAuthException

    MIDDLEWARE_CLASSES += (
        'social.apps.django_app.middleware.SocialAuthExceptionMiddleware',
    )
    
  2. URL to redirect to, when an exception occurred

    SOCIAL_AUTH_LOGIN_ERROR_URL = '/'
    
  3. Note that you also need to set

    DEBUG = False
    

That's all or read http://python-social-auth.readthedocs.org/en/latest/configuration/django.html#exceptions-middleware

Gooseberry answered 19/8, 2014 at 16:11 Comment(4)
finally an answer that works for the newer version! thanks :)Such
The key part for me was to set DEBUG = False This was driving me nuts, thanks for the answer!Karat
Thanks Man..worked like charm. I am really thankful to stackoverflow. Its magic!Handout
I sure did not found the DEBUG has to be False in docs of the Module or maybe it was not clear. Anyway it worked like a charm for me too.Circulation
K
21

you can create a middleware and catch any exceptions, exception list: https://github.com/omab/python-social-auth/blob/master/social/exceptions.py in this case your AuthCanceled Exception.

middleware.py



from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import HttpResponse
from social import exceptions as social_exceptions

class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
    def process_exception(self, request, exception):
        if hasattr(social_exceptions, 'AuthCanceled'):
            return HttpResponse("I'm the Pony %s" % exception)
        else:
            raise exception


settings.py



MIDDLEWARE_CLASSES = (
        .....
        'pat_to_middleware.SocialAuthExceptionMiddleware',
)


Klement answered 6/1, 2014 at 20:26 Comment(3)
hasattr(social_exceptions, 'AuthCanceled') returns true even if the exception is not AuthCanceled. It catches all other errors even 404.Kistner
Caution, this will not work if INSTALLED_APPS includes 'debug_toolbar' as it wraps the middleware and prevents the exception from percolating through the process_exception functionsLeicestershire
Yes, it's only an example.Unreal
K
18

This is slight modification of @Nicolas answer and this works for me.

middleware.py

from social.apps.django_app.middleware import SocialAuthExceptionMiddleware
from django.shortcuts import render
from social.exceptions import AuthCanceled

class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
    def process_exception(self, request, exception):
        if type(exception) == AuthCanceled:
            return render(request, "pysocial/authcancelled.html", {})
        else:
            pass

settings.py

MIDDLEWARE_CLASSES += (
'myapp.middleware.SocialAuthExceptionMiddleware',
)
Kistner answered 20/2, 2014 at 6:28 Comment(3)
Its from social_auth.middleware import SocialAuthExceptionMiddlewareAttalie
@Chipmunk This answer is for python-social-auth , not for django-social-auth.Kistner
Its better to use different name for middleware than default class name SocialAuthExceptionMiddleware for clarity (which is matching the import)Eisenstark
G
5

The 2018 answer:

  1. Add SocialAuthExceptionMiddleware middleware to your config:

    MIDDLEWARE_CLASSES = [
        ...
        'social_django.middleware.SocialAuthExceptionMiddleware',
    ]
    
  2. Set SOCIAL_AUTH_LOGIN_ERROR_URL in your config:

    SOCIAL_AUTH_LOGIN_ERROR_URL = '/login'
    

Now when you have DEBUG = False, your users will get redirected to your login page when they click cancel in social auth provider's page.

When DEBUG = True you will still see the error page in your browser during development.

Glowing answered 29/1, 2018 at 14:12 Comment(1)
As of 2020, this is the correct answer -- have verified with social-auth-app-django 4.0.0 and Django 3.0Priceless
S
2

Just add in

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

and something like

LOGIN_ERROR_URL = '/'

That's all or read http://django-social-auth.readthedocs.org/en/latest/configuration.html#exceptions-middleware

Sliding answered 27/2, 2014 at 5:36 Comment(1)
Note that this does not work for python-social-auth, the newer version. See @nattster's answer for the correct method.Holsinger
R
2

If you don't care about handling the exception do the following in your settings.py

SOCIAL_AUTH_RAISE_EXCEPTIONS = False

See this answer: How to solve Authentication process canceled error?

Rigel answered 15/11, 2016 at 21:14 Comment(0)
M
0

This is a updated imports middleware using social_django

from social_django.middleware import SocialAuthExceptionMiddleware
from social_core import exceptions as social_exceptions
from django.shortcuts import HttpResponse
from django.shortcuts import render, redirect

class FacebookAuthCanceledExceptionMiddleware(SocialAuthExceptionMiddleware):

    def process_exception(self, request, exception):
        if hasattr(social_exceptions, 'AuthCanceled'):
            return redirect('auth_login')
        else:
            raise exception
Mick answered 30/11, 2017 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.