~andreserl/maas/lp1570609

« back to all changes in this revision

Viewing changes to src/maasserver/middleware.py

  • Committer: MAAS Lander
  • Author(s): Raphael Badin, Blake Rouse
  • Date: 2016-04-13 16:12:47 UTC
  • mfrom: (3492.6.8 bug-1298772-protect)
  • Revision ID: maas_lander-20160413161247-92v6u2b7rxvggwlr
[r=allenap][bug=1298772][author=maas-maintainers] Enable CSRF protection on the API unless OAuth authentication is being used.

Show diffs side-by-side

added added

removed removed

Lines of Context:
351
351
            response['Retry-After'] = (
352
352
                RETRY_AFTER_SERVICE_UNAVAILABLE)
353
353
        return response
 
354
 
 
355
 
 
356
class CSRFHelperMiddleware:
 
357
    """A Middleware to decide whether a request needs to be protected against
 
358
    CSRF attacks.
 
359
 
 
360
    Requests with a session cookie (i.e. requests for which the basic
 
361
    session-based Django authentification is used) will be CSRF protected.
 
362
    Requests without this cookie are pure 0-legged API requests and thus don't
 
363
    need to use the CSRF protection machinery because each request is signed.
 
364
    """
 
365
 
 
366
    def process_request(self, request):
 
367
        session_cookie = request.COOKIES.get(
 
368
            settings.SESSION_COOKIE_NAME, None)
 
369
        if session_cookie is None:
 
370
            # csrf_processing_done is a field used by Django.  We use it here
 
371
            # to bypass the CSRF protection when it's not needed (i.e. when the
 
372
            # request is OAuth-authenticated).
 
373
            request.csrf_processing_done = True
 
374
        return None