add PassiveAuthenticationMiddleware using a common domain cookie (fixes #8123)

Name of the cookie must be put in MELLON_OPENED_SESSION_COOKIE_NAME and
common domain can be defined in MELLON_OPENED_SESSION_COOKIE_DOMAIN, if
unset the common domain is guessed by removing the first part of the
domain name (www.xxx.com -> xxx.com).
This commit is contained in:
Benjamin Dauvergne 2015-09-24 10:22:11 +02:00
parent 0e57f99312
commit 9667aa5f18
2 changed files with 42 additions and 0 deletions

View File

@ -27,6 +27,8 @@ class AppSettings(object):
'ERROR_REDIRECT_AFTER_TIMEOUT': 120,
'DEFAULT_ASSERTION_CONSUMER_BINDING': 'post', # or artifact
'VERIFY_SSL_CERTIFICATE': True,
'OPENED_SESSION_COOKIE_NAME': None,
'OPENED_SESSION_COOKIE_DOMAIN': None,
}
@property

40
mellon/middleware.py Normal file
View File

@ -0,0 +1,40 @@
from django.utils.http import urlencode
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from . import app_settings
PASSIVE_TRIED_COOKIE = 'MELLON_PASSIVE_TRIED'
class PassiveAuthenticationMiddleware(object):
def process_response(self, request, response):
# When unlogged remove the PASSIVE_TRIED cookie
if app_settings.OPENED_SESSION_COOKIE_NAME \
and PASSIVE_TRIED_COOKIE in request.COOKIES \
and app_settings.OPENED_SESSION_COOKIE_NAME not in request.COOKIES:
response.delete_cookie(PASSIVE_TRIED_COOKIE)
return response
def process_request(self, request):
if not app_settings.OPENED_SESSION_COOKIE_NAME:
return
if hasattr(request, 'user') and request.user.is_authenticated():
return
if PASSIVE_TRIED_COOKIE in request.COOKIES:
return
if app_settings.OPENED_SESSION_COOKIE_NAME in request.COOKIES:
# get the common domain or guess
common_domain = app_settings.OPENED_SESSION_COOKIE_DOMAIN
if not common_domain:
common_domain = request.META['SERVER_NAME'].split('.', 1)[1]
assert '.' in commom_domain # if domain is xxx.com explode !
params = {
'next': request.build_absolute_uri(),
'passive': '',
}
url = reverse('mellon_login') + '?%s' % urlencode(params)
response = HttpResponseRedirect(url)
# prevent loops
response.set_cookie(PASSIVE_TRIED_COOKIE, value='1', max_age=None)
return response