From 35022ca9213939a2f40c82facffa908a818efe0b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sat, 29 Jun 2013 08:14:05 +0100 Subject: [PATCH] Refactor SessionAuthentication slightly --- rest_framework/authentication.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 102980271..b42162dd9 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -26,6 +26,12 @@ def get_authorization_header(request): return auth +class CSRFCheck(CsrfViewMiddleware): + def _reject(self, request, reason): + # Return the failure reason instead of an HttpResponse + return reason + + class BaseAuthentication(object): """ All authentication classes should extend BaseAuthentication. @@ -110,20 +116,20 @@ class SessionAuthentication(BaseAuthentication): if not user or not user.is_active: return None - # Enforce CSRF validation for session based authentication. - class CSRFCheck(CsrfViewMiddleware): - def _reject(self, request, reason): - # Return the failure reason instead of an HttpResponse - return reason - - reason = CSRFCheck().process_view(http_request, None, (), {}) - if reason: - # CSRF failed, bail with explicit error message - raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason) + self.enforce_csrf(http_request) # CSRF passed with authenticated user return (user, None) + def enforce_csrf(self, request): + """ + Enforce CSRF validation for session based authentication. + """ + reason = CSRFCheck().process_view(request, None, (), {}) + if reason: + # CSRF failed, bail with explicit error message + raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason) + class TokenAuthentication(BaseAuthentication): """