from django.contrib import auth from django.utils.deprecation import MiddlewareMixin from django.core.exceptions import ImproperlyConfigured from .settings import sso_settings class SsoMiddleware(MiddlewareMixin): def process_request(self, request): if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the pingcap_cookie_sso.middleware.SsoMiddleware class.") try: sso_session_id = request.COOKIES[sso_settings.SSO_COOKIE_NAME] except KeyError: if request.user.is_authenticated: auth.logout(request) return if not request.user.is_authenticated and sso_session_id: user = auth.authenticate(request, sso_session_id=sso_session_id) if user: request.user = user auth.login(request, user) else: request._sso_auth_failed = True