def get_user(request): if not hasattr(request, '_cached_user'): user = auth_get_user(request) # If the user bound to this request matches a real user, # we need to validate the session's nonce. This nonce is # to make sure that the session is valid for effectively the # current "version" of the user. When security related # actions take place, this nonce will rotate causing a # mismatch here forcing the session to be logged out and # requiring re-validation. if user.is_authenticated(): # We only need to check the nonce if there is a nonce # currently set on the User. By default, the value will # be None until the first action has been taken, at # which point, a nonce will always be required. if user.session_nonce and request.session.get('_nonce', '') != user.session_nonce: # If the nonces don't match, this session is anonymous. logger.info( 'user.auth.invalid-nonce', extra={ 'ip_address': request.META['REMOTE_ADDR'], 'user_id': user.id, } ) user = AnonymousUser() else: UserIP.log(user, request.META['REMOTE_ADDR']) request._cached_user = user return request._cached_user
def get_user(request): if not hasattr(request, '_cached_user'): user = auth_get_user(request) # If the user bound to this request matches a real user, # we need to validate the session's nonce. This nonce is # to make sure that the session is valid for effectively the # current "version" of the user. When security related # actions take place, this nonce will rotate causing a # mismatch here forcing the session to be logged out and # requiring re-validation. if user.is_authenticated() and not user.is_sentry_app: # We only need to check the nonce if there is a nonce # currently set on the User. By default, the value will # be None until the first action has been taken, at # which point, a nonce will always be required. if user.session_nonce and request.session.get('_nonce', '') != user.session_nonce: # If the nonces don't match, this session is anonymous. logger.info( 'user.auth.invalid-nonce', extra={ 'ip_address': request.META['REMOTE_ADDR'], 'user_id': user.id, } ) user = AnonymousUser() else: UserIP.log(user, request.META['REMOTE_ADDR']) request._cached_user = user return request._cached_user
def get_user(context): from django.utils.functional import LazyObject if settings.TESTING: user = context.user if isinstance(user, LazyObject): return user._wrapped # pylint: disable=W0212 return user return auth_get_user(context)
def assertUserIsNotAuthenticated(self): """Assert the user is *not* authenticated.""" user = auth_get_user(self.client) self.assertFalse(user.is_authenticated)
def assertUserIsAuthenticated(self): """Assert the user is authenticated.""" user = auth_get_user(self.client) self.assertTrue(user.is_authenticated)
def test_full_login_process(self): """Asserts the nominal login process works.""" sso_location = "http://testserver/account/saml/local-accepting-idp/sso/" entity_descriptor_list = [ generate_idp_metadata( entity_id=sso_location, sso_location=sso_location, ui_info_display_names=format_mdui_display_name( "Local accepting IdP"), ), ] # 1/ Select Idp in the provider list with mock.patch("urllib.request.urlopen") as urlopen_mock: class UrlOpenMock: """Mockin object for the urlopen""" def read(self): """Allow object to be read several times.""" return generate_idp_federation_metadata( entity_descriptor_list=entity_descriptor_list, ).encode("utf-8") urlopen_mock.return_value = UrlOpenMock() response = self.client.get( reverse("account:saml_fer_idp_choice"), ) self.assertContains( response, f'action="{reverse("account:social:begin", args=("saml_fer",))}"', ) self.assertContains(response, "local-accepting-idp") response = self.client.get( f'{reverse("account:social:begin", args=("saml_fer",))}?idp=local-accepting-idp', ) self.assertEqual(response.status_code, 302) self.assertTrue(response["Location"].startswith( "http://testserver/account/saml/local-accepting-idp/sso/?SAMLRequest=" )) # 2/ Fake the redirection to the SSO response = self.client.get( f'{reverse("account:social:begin", args=("saml_fer",))}?idp=local-accepting-idp', follow=False, ) # 3/ Generate SAML response using SAML request query_values = parse_qs(urlparse(response["Location"]).query) saml_request = query_values["SAMLRequest"] saml_relay_state = query_values["RelayState"] readable_saml_request = OneLogin_Saml2_Utils.decode_base64_and_inflate( saml_request, ) saml_request = OneLogin_Saml2_XML.to_etree(readable_saml_request) saml_acs_url = saml_request.get("AssertionConsumerServiceURL") request_id = saml_request.get("ID") auth_response = OneLogin_Saml2_Utils.b64encode( generate_auth_response( request_id, saml_acs_url, issuer= "http://testserver/account/saml/local-accepting-idp/sso/", )) # 4/ POST the data to our endpoint response = self.client.post( saml_acs_url, data={ "RelayState": saml_relay_state, "SAMLResponse": auth_response, }, ) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "/") # Assert the user is authenticated user = auth_get_user(self.client) self.assertTrue(user.is_authenticated) # Assert the user has an organization organization_access = user.organization_accesses.select_related( "organization").get() # also assert there is only one organization self.assertEqual(organization_access.role, STUDENT) self.assertEqual(organization_access.organization.name, "OrganizationDName")