From 984179d76c19b6674b4e96545e23bc3a042e92a1 Mon Sep 17 00:00:00 2001 From: Marcel Kornblum Date: Fri, 28 Apr 2023 14:01:47 +0100 Subject: [PATCH] split authenticate into separate overridable function (#1) * split authenticate into separate overridable function * cleaner exception * basic unit test * remove new test * space to revert change --- djangosaml2/views.py | 47 ++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/djangosaml2/views.py b/djangosaml2/views.py index 9b2d9e93..86ea19d1 100644 --- a/djangosaml2/views.py +++ b/djangosaml2/views.py @@ -550,7 +550,40 @@ def post(self, request, attribute_mapping=None, create_unknown_user=None): if callable(create_unknown_user): create_unknown_user = create_unknown_user() + try: + user = self.authenticate_user( + request, + session_info, + attribute_mapping, + create_unknown_user, + assertion_info + ) + except PermissionDenied as e: + return self.handle_acs_failure( + request, + exception=e, + session_info=session_info, + ) + + relay_state = self.build_relay_state() + custom_redirect_url = self.custom_redirect(user, relay_state, session_info) + if custom_redirect_url: + return HttpResponseRedirect(custom_redirect_url) + relay_state = validate_referral_url(request, relay_state) + logger.debug("Redirecting to the RelayState: %s", relay_state) + return HttpResponseRedirect(relay_state) + + def authenticate_user( + self, + request, + session_info, + attribute_mapping, + create_unknown_user, + assertion_info + ): + """Calls Django's authenticate method after the SAML response is verified""" logger.debug("Trying to authenticate the user. Session info: %s", session_info) + user = auth.authenticate( request=request, session_info=session_info, @@ -563,11 +596,7 @@ def post(self, request, attribute_mapping=None, create_unknown_user=None): "Could not authenticate user received in SAML Assertion. Session info: %s", session_info, ) - return self.handle_acs_failure( - request, - exception=PermissionDenied("No user could be authenticated."), - session_info=session_info, - ) + raise PermissionDenied("No user could be authenticated.") auth.login(self.request, user) _set_subject_id(request.saml_session, session_info["name_id"]) @@ -576,14 +605,6 @@ def post(self, request, attribute_mapping=None, create_unknown_user=None): self.post_login_hook(request, user, session_info) self.customize_session(user, session_info) - relay_state = self.build_relay_state() - custom_redirect_url = self.custom_redirect(user, relay_state, session_info) - if custom_redirect_url: - return HttpResponseRedirect(custom_redirect_url) - relay_state = validate_referral_url(request, relay_state) - logger.debug("Redirecting to the RelayState: %s", relay_state) - return HttpResponseRedirect(relay_state) - def post_login_hook( self, request: HttpRequest, user: settings.AUTH_USER_MODEL, session_info: dict ) -> None: