Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion common/djangoapps/third_party_auth/middleware.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
"""Middleware classes for third_party_auth."""


import json
import urllib.parse

import six.moves.urllib.parse
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import gettext as _
from requests import HTTPError
from social_core.exceptions import SocialAuthBaseException
from social_django.middleware import SocialAuthExceptionMiddleware

from common.djangoapps.student.helpers import get_next_url_for_login_page

from . import pipeline
from . import pipeline, provider


def _get_saml_provider_name(request):
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_get_saml_provider_name within the middleware to construct a direct URL to the MFE with ?duplicate_provider=. While this resolves the specific SAML case, I'm a bit concerned about extensibility and long-term maintainability. I'd like to share why I think it would be better to move this logic to a custom view (such as AccountSettingsRedirectView) that handles the error context in a more generic way.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, just a thought on this — I think we could improve the overall design by moving the redirect logic to a custom view (e.g. AccountSettingsRedirectView) instead of handling it inside the middleware. Here's my reasoning:

  • Centralizes redirect logic: The view would be responsible for reading error messages from django.contrib.messages (or the session) and deciding how to pass them to the MFE. That way the middleware only needs to store the error (e.g. via messages.error(...)) and doesn't need to know anything about URL construction.

  • Extensible to any provider: Any backend (SAML, OAuth, LTI) can add a message with extra_tags='social-auth' and the view will pick it up automatically — no need for provider-specific helper functions like _get_saml_provider_name.

  • Cleaner separation of concerns: The middleware handles exceptions and stores errors; the view handles the redirect and forwards the error to the MFE. This makes both pieces easier to test and reason about independently.

  • Easier to evolve the MFE communication layer: If we ever decide to switch from URL params to an API endpoint, we only update the view — not the middleware. For example, the view could store the error in the session and the MFE could fetch it via a call to /api/user/v1/tpa_errors/.

"""
Try to resolve the human-readable provider name from the SAML RelayState
that is present in the POST body of /auth/complete/tpa-saml/.

Returns the provider display name (e.g. "Cartão de Cidadão") or None if
it cannot be determined.
"""
try:
backend = getattr(request, 'backend', None)
if backend is None:
return None
relay_state_str = backend.strategy.request_data().get('RelayState', '')
relay_state = json.loads(relay_state_str)
idp_slug = relay_state.get('idp')
if not idp_slug:
return None
# provider_id for SAML providers is "saml-<slug>"
saml_provider = provider.Registry.get(f'saml-{idp_slug}')
if saml_provider:
return saml_provider.name
except Exception: # pylint: disable=broad-except
pass
return None


class ExceptionMiddleware(SocialAuthExceptionMiddleware, MiddlewareMixin):
Expand All @@ -32,6 +63,25 @@ def get_redirect_uri(self, request, exception):
if auth_entry and auth_entry in pipeline.AUTH_DISPATCH_URLS:
redirect_uri = pipeline.AUTH_DISPATCH_URLS[auth_entry]

# For the account_settings SAML flow, /account/settings is a plain RedirectView
# that goes to the Account MFE without preserving Django messages. Build the
# MFE URL directly so the ?duplicate_provider param reaches the frontend.
# This only applies to the tpa-saml backend; OAuth providers are handled by
# the existing get_duplicate_provider() path in settings_views.account_settings().
backend_name = getattr(getattr(request, 'backend', None), 'name', None)
if (
auth_entry == pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS
and isinstance(exception, SocialAuthBaseException)
and backend_name == 'tpa-saml'
):
account_mfe_url = getattr(settings, 'ACCOUNT_MICROFRONTEND_URL', None)
if account_mfe_url:
provider_name = _get_saml_provider_name(request) or backend_name
redirect_uri = '{}?duplicate_provider={}'.format(
account_mfe_url.rstrip('/') + '/',
urllib.parse.quote(provider_name, safe=''),
)

return redirect_uri

def process_exception(self, request, exception):
Expand Down
Loading