The right way of AuthCanceled exception handling

944 views
Skip to first unread message

Alexander Burtsev

unread,
Mar 12, 2013, 7:15:20 AM3/12/13
to django-so...@googlegroups.com
Hi!

I'm using Django Social Auth for Google OpenID authentication.

urls.py fragment:

```
url(r'', include('social_auth.urls')),
```

But a can't handle exception AuthCanceled. It's settings don't help me:

```
DEBUG = False

SOCIAL_AUTH_RAISE_EXCEPTIONS = False
SOCIAL_AUTH_BACKEND_ERROR_URL = '/login_error/'
LOGIN_ERROR_URL = '/login_error/'
```

I change urls.py and write them all routes directly:

```
  #url(r'', include('social_auth.urls')),

  url(r'^login/(?P<backend>[^/]+)/$', 'social_auth.views.auth', name='socialauth_begin'),
  url(r'^complete/(?P<backend>[^/]+)/$', 'www.views.complete_view', name='socialauth_complete'),
```

And override complete view:

```
from social_auth.views import complete
from social_auth.exceptions import AuthCanceled

def complete_view(request, backend, *args, **kwargs):
  try:
    return complete(request, backend, *args, **kwargs)
  except AuthCanceled as e:
    return render_to_response('index.html', { 'auth_canceled': True })
```

It's worked! But I think, it's not best practice.

Matías Aguirre

unread,
Mar 14, 2013, 1:19:01 PM3/14/13
to django-social-auth
Hi Alexander,

The proper way is to register DSA middleware[1], or subclass it and override
any method to accomplish your desired effect. For example, this version could
to a similar work and you don't need to override URLs and views:

from social_auth.middleware import SocialAuthExceptionMiddleware
from social_auth.exceptions import AuthCanceled

class RedirectOnCancelMiddleware(SocialAuthExceptionMiddleware):
def get_redirect_uri(self, request, exception):
if isinstance(exception, AuthCanceled):
return '/auth-canceled'
else:
return super(RedirectOnCancelMiddleware, self).get_redirect_uri(request, exception)


Then, register an /auth-canceled URL and view for it.

[1]: https://github.com/omab/django-social-auth/blob/master/social_auth/middleware.py#L10

Matías

Excerpts from Alexander Burtsev's message of 2013-03-12 08:15:20 -0300:
--
Matías Aguirre (matias...@gmail.com)

Pau Argelaguet

unread,
Jan 5, 2016, 1:43:40 PM1/5/16
to Django Social Auth
Hi Matías,

I've created a file called middleware.py containing your code, but I don't know how to register this middleware. Could you be more specific on that?

Thanks,

Pau
Reply all
Reply to author
Forward
0 new messages