def base_extauth_bypass_sending_activation_email(self, bypass_activation_email):
        """
        Tests user creation without sending activation email when
        doing external auth
        """

        request = self.request_factory.post(self.url, self.params)
        request.site = self.site
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(external_id='*****@*****.**',
                                  external_email='*****@*****.**',
                                  internal_password=self.params['password'],
                                  external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        with mock.patch('edxmako.request_context.get_current_request', return_value=request):
            with mock.patch('edx_ace.ace.send') as mock_send_mail:
                create_account(request)

        # check that send_mail is called
        if bypass_activation_email:
            self.assertFalse(mock_send_mail.called)
        else:
            self.assertTrue(mock_send_mail.called)
예제 #2
0
    def base_extauth_bypass_sending_activation_email(self,
                                                     bypass_activation_email):
        """
        Tests user creation without sending activation email when
        doing external auth
        """

        request = self.request_factory.post(self.url, self.params)
        request.site = self.site
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(
            settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(
            external_id='*****@*****.**',
            external_email='*****@*****.**',
            internal_password=self.params['password'],
            external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        with mock.patch('edxmako.request_context.get_current_request',
                        return_value=request):
            with mock.patch('django.core.mail.send_mail') as mock_send_mail:
                create_account(request)

        # check that send_mail is called
        if bypass_activation_email:
            self.assertFalse(mock_send_mail.called)
        else:
            self.assertTrue(mock_send_mail.called)
예제 #3
0
파일: base.py 프로젝트: bondak/edx-platform
 def test_new_account_registration_fails_if_email_exists(self):
     request, strategy = self.get_request_and_strategy(
         auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
     strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
     # pylint:disable-msg=protected-access
     self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))
     self.assert_register_response_in_pipeline_looks_correct(
         student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])
     strategy.request.POST = self.get_registration_post_vars()
     # Create twice: once successfully, and once causing a collision.
     student_views.create_account(strategy.request)
     self.assert_json_failure_response_is_username_collision(student_views.create_account(strategy.request))
예제 #4
0
 def test_new_account_registration_fails_if_email_exists(self):
     request, strategy = self.get_request_and_strategy(
         auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
     strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
     # pylint:disable-msg=protected-access
     self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))
     self.assert_register_response_in_pipeline_looks_correct(
         student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])
     strategy.request.POST = self.get_registration_post_vars()
     # Create twice: once successfully, and once causing a collision.
     student_views.create_account(strategy.request)
     self.assert_json_failure_response_is_username_collision(student_views.create_account(strategy.request))
예제 #5
0
    def test_registration_form_submit(self, identity):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        # First we pop the registration form
        client = DjangoTestClient()
        response1 = client.get(path='/shib-login/', data={}, follow=False, **identity)
        # Then we have the user answer the registration form
        # These are unicode because request.POST returns unicode
        postvars = {'email': u'*****@*****.**',
                    'username': u'post_username',  # django usernames can't be unicode
                    'password': u'post_pássword',
                    'name': u'post_náme',
                    'terms_of_service': u'true',
                    'honor_code': u'true'}
        # use RequestFactory instead of TestClient here because we want access to request.user
        request2 = self.request_factory.post('/create_account', data=postvars)
        request2.session = client.session
        request2.user = AnonymousUser()

        mako_middleware_process_request(request2)
        with patch('student.views.AUDIT_LOG') as mock_audit_log:
            _response2 = create_account(request2)

        user = request2.user
        mail = identity.get('mail')
예제 #6
0
    def test_full_pipeline_succeeds_registering_new_account(self):
        # First, create, the request and strategy that store pipeline state.
        # Mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))

        # Begin! Grab the registration page and check the login control on it.
        self.assert_register_response_before_pipeline_looks_correct(self.client.get('/register'))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN)))

        # Next, the provider makes a request against /auth/complete/<provider>.
        # pylint:disable-msg=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the registration form.
        self.assert_register_response_in_pipeline_looks_correct(
            student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])

        # Next, we invoke the view that handles the POST. Not all providers
        # supply email. Manually add it as the user would have to; this
        # also serves as a test of overriding provider values. Always provide a
        # password for us to check that we override it properly.
        overridden_password = strategy.request.POST.get('password')
        email = '*****@*****.**'

        if not strategy.request.POST.get('email'):
            strategy.request.POST = self.get_registration_post_vars({'email': email})

        # The user must not exist yet...
        with self.assertRaises(auth_models.User.DoesNotExist):
            self.get_user_by_email(strategy, email)

        # ...but when we invoke create_account the existing edX view will make
        # it, but not social auths. The pipeline creates those later.
        self.assert_json_success_response_looks_correct(student_views.create_account(strategy.request))
        # We've overridden the user's password, so authenticate() with the old
        # value won't work:
        created_user = self.get_user_by_email(strategy, email)
        self.assert_password_overridden_by_pipeline(overridden_password, created_user.username)

        # At this point the user object exists, but there is no associated
        # social auth.
        self.assert_social_auth_does_not_exist_for_user(created_user, strategy)

        # Pick the pipeline back up. This will create the account association
        # and send the user to the dashboard, where the association will be
        # displayed.
        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy, social_views._do_login, user=created_user))
        self.assert_social_auth_exists_for_user(created_user, strategy)
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), created_user, linked=True)
예제 #7
0
    def test_full_pipeline_succeeds_registering_new_account(self):
        # First, create, the request and strategy that store pipeline state.
        # Mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))

        # Begin! Grab the registration page and check the login control on it.
        self.assert_register_response_before_pipeline_looks_correct(self.client.get('/register'))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN)))

        # Next, the provider makes a request against /auth/complete/<provider>.
        # pylint:disable-msg=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))

        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the registration form.
        self.assert_register_response_in_pipeline_looks_correct(
            student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])

        # Next, we invoke the view that handles the POST. Not all providers
        # supply email. Manually add it as the user would have to; this
        # also serves as a test of overriding provider values. Always provide a
        # password for us to check that we override it properly.
        overridden_password = strategy.request.POST.get('password')
        email = '*****@*****.**'

        if not strategy.request.POST.get('email'):
            strategy.request.POST = self.get_registration_post_vars({'email': email})

        # The user must not exist yet...
        with self.assertRaises(auth_models.User.DoesNotExist):
            self.get_user_by_email(strategy, email)

        # ...but when we invoke create_account the existing edX view will make
        # it, but not social auths. The pipeline creates those later.
        self.assert_json_success_response_looks_correct(student_views.create_account(strategy.request))
        # We've overridden the user's password, so authenticate() with the old
        # value won't work:
        created_user = self.get_user_by_email(strategy, email)
        self.assert_password_overridden_by_pipeline(overridden_password, created_user.username)

        # At this point the user object exists, but there is no associated
        # social auth.
        self.assert_social_auth_does_not_exist_for_user(created_user, strategy)

        # Pick the pipeline back up. This will create the account association
        # and send the user to the dashboard, where the association will be
        # displayed.
        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy, social_views._do_login, user=created_user))
        self.assert_social_auth_exists_for_user(created_user, strategy)
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), created_user, linked=True)
예제 #8
0
    def test_registration_formSubmit(self):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        for identity in gen_all_identities():
            #First we pop the registration form
            client = DjangoTestClient()
            response1 = client.get(path='/shib-login/', data={}, follow=False, **identity)
            #Then we have the user answer the registration form
            postvars = {'email': '*****@*****.**',
                        'username': '******',
                        'password': '******',
                        'name': 'post_name',
                        'terms_of_service': 'true',
                        'honor_code': 'true'}
            #use RequestFactory instead of TestClient here because we want access to request.user
            request2 = self.request_factory.post('/create_account', data=postvars)
            request2.session = client.session
            request2.user = AnonymousUser()
            response2 = create_account(request2)

            user = request2.user
            mail = identity.get('mail')
            #check that the created user has the right email, either taken from shib or user input
            if mail:
                self.assertEqual(user.email, mail)
                self.assertEqual(list(User.objects.filter(email=postvars['email'])), [])
                self.assertIsNotNone(User.objects.get(email=mail))  # get enforces only 1 such user
            else:
                self.assertEqual(user.email, postvars['email'])
                self.assertEqual(list(User.objects.filter(email=mail)), [])
                self.assertIsNotNone(User.objects.get(email=postvars['email']))  # get enforces only 1 such user

            #check that the created user profile has the right name, either taken from shib or user input
            profile = UserProfile.objects.get(user=user)
            sn_empty = not identity.get('sn')
            given_name_empty = not identity.get('givenName')
            if sn_empty and given_name_empty:
                self.assertEqual(profile.name, postvars['name'])
            else:
                self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name)
            #clean up for next loop
            request2.session['ExternalAuthMap'].delete()
            UserProfile.objects.filter(user=user).delete()
            Registration.objects.filter(user=user).delete()
            user.delete()
    def test_registration_formSubmit(self):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        for identity in gen_all_identities():
            #First we pop the registration form
            client = DjangoTestClient()
            response1 = client.get(path='/shib-login/', data={}, follow=False, **identity)
            #Then we have the user answer the registration form
            postvars = {'email': '*****@*****.**',
                        'username': '******',
                        'password': '******',
                        'name': 'post_name',
                        'terms_of_service': 'true',
                        'honor_code': 'true'}
            #use RequestFactory instead of TestClient here because we want access to request.user
            request2 = self.request_factory.post('/create_account', data=postvars)
            request2.session = client.session
            request2.user = AnonymousUser()
            response2 = create_account(request2)

            user = request2.user
            mail = identity.get('mail')
            #check that the created user has the right email, either taken from shib or user input
            if mail:
                self.assertEqual(user.email, mail)
                self.assertEqual(list(User.objects.filter(email=postvars['email'])), [])
                self.assertIsNotNone(User.objects.get(email=mail))  # get enforces only 1 such user
            else:
                self.assertEqual(user.email, postvars['email'])
                self.assertEqual(list(User.objects.filter(email=mail)), [])
                self.assertIsNotNone(User.objects.get(email=postvars['email']))  # get enforces only 1 such user

            #check that the created user profile has the right name, either taken from shib or user input
            profile = UserProfile.objects.get(user=user)
            sn_empty = not identity.get('sn')
            given_name_empty = not identity.get('givenName')
            if sn_empty and given_name_empty:
                self.assertEqual(profile.name, postvars['name'])
            else:
                self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name)
            #clean up for next loop
            request2.session['ExternalAuthMap'].delete()
            UserProfile.objects.filter(user=user).delete()
            Registration.objects.filter(user=user).delete()
            user.delete()
예제 #10
0
 def test_ext_auth_password_length_too_short(self):
     """
     Tests that even if password policy is enforced, ext_auth registrations aren't subject to it
     """
     self.url_params['password'] = '******'  # shouldn't pass validation
     request = self.request_factory.post(self.url, self.url_params)
     # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
     request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
     extauth = ExternalAuthMap(external_id='*****@*****.**',
                               external_email='*****@*****.**',
                               internal_password=self.url_params['password'],
                               external_domain='shib:https://idp.stanford.edu/')
     request.session['ExternalAuthMap'] = extauth
     response = create_account(request)
     self.assertEqual(response.status_code, 200)
     obj = json.loads(response.content)
     self.assertTrue(obj['success'])
예제 #11
0
    def test_ext_auth_password_length_too_short(self):
        """
        Tests that even if password policy is enforced, ext_auth registrations aren't subject to it
        """
        self.url_params['password'] = '******'  # shouldn't pass validation
        request = self.request_factory.post(self.url, self.url_params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(external_id='*****@*****.**',
                                  external_email='*****@*****.**',
                                  internal_password=self.url_params['password'],
                                  external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        with patch('edxmako.request_context.get_current_request', return_value=request):
            response = create_account(request)
        self.assertEqual(response.status_code, 200)
        obj = json.loads(response.content)
        self.assertTrue(obj['success'])
    def test_ext_auth_password_length_too_short(self):
        """
        Tests that even if password policy is enforced, ext_auth registrations aren't subject to it
        """
        self.url_params["password"] = "******"  # shouldn't pass validation
        request = self.request_factory.post(self.url, self.url_params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(
            external_id="*****@*****.**",
            external_email="*****@*****.**",
            internal_password=self.url_params["password"],
            external_domain="shib:https://idp.stanford.edu/",
        )
        request.session["ExternalAuthMap"] = extauth
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        response = create_account(request)
        self.assertEqual(response.status_code, 200)
        obj = json.loads(response.content)
        self.assertTrue(obj["success"])
예제 #13
0
    def test_registration_form_submit(self, identity):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        # First we pop the registration form
        client = DjangoTestClient()
        response1 = client.get(path='/shib-login/', data={}, follow=False, **identity)
        # Then we have the user answer the registration form
        # These are unicode because request.POST returns unicode
        postvars = {'email': u'*****@*****.**',
                    'username': u'post_username',  # django usernames can't be unicode
                    'password': u'post_pássword',
                    'name': u'post_náme',
                    'terms_of_service': u'true',
                    'honor_code': u'true'}
        # use RequestFactory instead of TestClient here because we want access to request.user
        request2 = self.request_factory.post('/create_account', data=postvars)
        request2.session = client.session
        request2.user = AnonymousUser()

        mako_middleware_process_request(request2)
        with patch('student.views.AUDIT_LOG') as mock_audit_log:
            _response2 = create_account(request2)

        user = request2.user
        mail = identity.get('mail')

        # verify logging of login happening during account creation:
        audit_log_calls = mock_audit_log.method_calls
        self.assertEquals(len(audit_log_calls), 3)
        method_name, args, _kwargs = audit_log_calls[0]
        self.assertEquals(method_name, 'info')
        self.assertEquals(len(args), 1)
        self.assertIn(u'Login success on new account creation', args[0])
        self.assertIn(u'post_username', args[0])
        method_name, args, _kwargs = audit_log_calls[1]
        self.assertEquals(method_name, 'info')
        self.assertEquals(len(args), 2)
        self.assertIn(u'User registered with external_auth', args[0])
        self.assertEquals(u'post_username', args[1])
        method_name, args, _kwargs = audit_log_calls[2]
        self.assertEquals(method_name, 'info')
        self.assertEquals(len(args), 3)
        self.assertIn(u'Updated ExternalAuthMap for ', args[0])
        self.assertEquals(u'post_username', args[1])
        self.assertEquals(u'*****@*****.**', args[2].external_id)

        # check that the created user has the right email, either taken from shib or user input
        if mail:
            self.assertEqual(user.email, mail)
            self.assertEqual(list(User.objects.filter(email=postvars['email'])), [])
            self.assertIsNotNone(User.objects.get(email=mail))  # get enforces only 1 such user
        else:
            self.assertEqual(user.email, postvars['email'])
            self.assertEqual(list(User.objects.filter(email=mail)), [])
            self.assertIsNotNone(User.objects.get(email=postvars['email']))  # get enforces only 1 such user

        # check that the created user profile has the right name, either taken from shib or user input
        profile = UserProfile.objects.get(user=user)
        sn_empty = not identity.get('sn')
        given_name_empty = not identity.get('givenName')
        displayname_empty = not identity.get('displayName')

        if displayname_empty:
            if sn_empty and given_name_empty:
                self.assertEqual(profile.name, postvars['name'])
            else:
                self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name)
                self.assertNotIn(u';', profile.name)
        else:
            self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name)
            self.assertEqual(profile.name, identity.get('displayName').decode('utf-8'))
예제 #14
0
    def test_full_pipeline_succeeds_registering_new_account(self):
        # First, create, the request and strategy that store pipeline state.
        # Mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri="social:complete"
        )
        strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))

        # Begin! Grab the registration page and check the login control on it.
        self.assert_register_response_before_pipeline_looks_correct(self.client.get("/register"))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(
            self.client.get(pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN))
        )

        # Next, the provider makes a request against /auth/complete/<provider>.
        # pylint: disable=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(request.backend, social_views._do_login))

        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the registration form.
        with self._patch_edxmako_current_request(request):
            self.assert_register_response_in_pipeline_looks_correct(
                student_views.register_user(strategy.request), pipeline.get(request)["kwargs"]
            )

        # Next, we invoke the view that handles the POST. Not all providers
        # supply email. Manually add it as the user would have to; this
        # also serves as a test of overriding provider values. Always provide a
        # password for us to check that we override it properly.
        overridden_password = strategy.request.POST.get("password")
        email = "*****@*****.**"

        if not strategy.request.POST.get("email"):
            strategy.request.POST = self.get_registration_post_vars({"email": email})

        # The user must not exist yet...
        with self.assertRaises(auth_models.User.DoesNotExist):
            self.get_user_by_email(strategy, email)

        # ...but when we invoke create_account the existing edX view will make
        # it, but not social auths. The pipeline creates those later.
        with self._patch_edxmako_current_request(strategy.request):
            self.assert_json_success_response_looks_correct(student_views.create_account(strategy.request))
        # We've overridden the user's password, so authenticate() with the old
        # value won't work:
        created_user = self.get_user_by_email(strategy, email)
        self.assert_password_overridden_by_pipeline(overridden_password, created_user.username)

        # At this point the user object exists, but there is no associated
        # social auth.
        self.assert_social_auth_does_not_exist_for_user(created_user, strategy)

        # We should be redirected back to the complete page, setting
        # the "logged in" cookie for the marketing site.
        self.assert_logged_in_cookie_redirect(
            actions.do_complete(
                request.backend,
                social_views._do_login,
                request.user,
                None,  # pylint: disable=protected-access
                redirect_field_name=auth.REDIRECT_FIELD_NAME,
            )
        )

        # Set the cookie and try again
        self.set_logged_in_cookies(request)
        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy.request.backend, social_views._do_login, user=created_user)
        )
        # Now the user has been redirected to the dashboard. Their third party account should now be linked.
        self.assert_social_auth_exists_for_user(created_user, strategy)
        self.assert_account_settings_context_looks_correct(account_settings_context(request), created_user, linked=True)
예제 #15
0
    def test_registration_form_submit(self):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        for identity in gen_all_identities():
            # First we pop the registration form
            client = DjangoTestClient()
            response1 = client.get(path='/shib-login/',
                                   data={},
                                   follow=False,
                                   **identity)
            # Then we have the user answer the registration form
            postvars = {
                'email': '*****@*****.**',
                'username': '******',
                'password': '******',
                'name': 'post_name',
                'terms_of_service': 'true',
                'honor_code': 'true'
            }
            # use RequestFactory instead of TestClient here because we want access to request.user
            request2 = self.request_factory.post('/create_account',
                                                 data=postvars)
            request2.session = client.session
            request2.user = AnonymousUser()
            with patch('student.views.AUDIT_LOG') as mock_audit_log:
                _response2 = create_account(request2)

            user = request2.user
            mail = identity.get('mail')

            # verify logging of login happening during account creation:
            audit_log_calls = mock_audit_log.method_calls
            self.assertEquals(len(audit_log_calls), 3)
            method_name, args, _kwargs = audit_log_calls[0]
            self.assertEquals(method_name, 'info')
            self.assertEquals(len(args), 1)
            self.assertIn(u'Login success on new account creation', args[0])
            self.assertIn(u'post_username', args[0])
            method_name, args, _kwargs = audit_log_calls[1]
            self.assertEquals(method_name, 'info')
            self.assertEquals(len(args), 2)
            self.assertIn(u'User registered with external_auth', args[0])
            self.assertEquals(u'post_username', args[1])
            method_name, args, _kwargs = audit_log_calls[2]
            self.assertEquals(method_name, 'info')
            self.assertEquals(len(args), 3)
            self.assertIn(u'Updated ExternalAuthMap for ', args[0])
            self.assertEquals(u'post_username', args[1])
            self.assertEquals(u'*****@*****.**', args[2].external_id)

            # check that the created user has the right email, either taken from shib or user input
            if mail:
                self.assertEqual(user.email, mail)
                self.assertEqual(
                    list(User.objects.filter(email=postvars['email'])), [])
                self.assertIsNotNone(User.objects.get(
                    email=mail))  # get enforces only 1 such user
            else:
                self.assertEqual(user.email, postvars['email'])
                self.assertEqual(list(User.objects.filter(email=mail)), [])
                self.assertIsNotNone(User.objects.get(
                    email=postvars['email']))  # get enforces only 1 such user

            # check that the created user profile has the right name, either taken from shib or user input
            profile = UserProfile.objects.get(user=user)
            sn_empty = not identity.get('sn')
            given_name_empty = not identity.get('givenName')
            displayname_empty = not identity.get('displayName')

            if displayname_empty:
                if sn_empty and given_name_empty:
                    self.assertEqual(profile.name, postvars['name'])
                else:
                    self.assertEqual(
                        profile.name,
                        request2.session['ExternalAuthMap'].external_name)
                    self.assertNotIn(u';', profile.name)
            else:
                self.assertEqual(
                    profile.name,
                    request2.session['ExternalAuthMap'].external_name)
                self.assertEqual(profile.name, identity.get('displayName'))

            # clean up for next loop
            request2.session['ExternalAuthMap'].delete()
            UserProfile.objects.filter(user=user).delete()
            Registration.objects.filter(user=user).delete()
            user.delete()
예제 #16
0
    def test_registration_form_submit(self):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        for identity in gen_all_identities():
            # First we pop the registration form
            client = DjangoTestClient()
            response1 = client.get(path="/shib-login/", data={}, follow=False, **identity)
            # Then we have the user answer the registration form
            postvars = {
                "email": "*****@*****.**",
                "username": "******",
                "password": "******",
                "name": "post_name",
                "terms_of_service": "true",
                "honor_code": "true",
            }
            # use RequestFactory instead of TestClient here because we want access to request.user
            request2 = self.request_factory.post("/create_account", data=postvars)
            request2.session = client.session
            request2.user = AnonymousUser()
            with patch("student.views.AUDIT_LOG") as mock_audit_log:
                _response2 = create_account(request2)

            user = request2.user
            mail = identity.get("mail")

            # verify logging of login happening during account creation:
            audit_log_calls = mock_audit_log.method_calls
            self.assertEquals(len(audit_log_calls), 3)
            method_name, args, _kwargs = audit_log_calls[0]
            self.assertEquals(method_name, "info")
            self.assertEquals(len(args), 1)
            self.assertIn(u"Login success on new account creation", args[0])
            self.assertIn(u"post_username", args[0])
            method_name, args, _kwargs = audit_log_calls[1]
            self.assertEquals(method_name, "info")
            self.assertEquals(len(args), 2)
            self.assertIn(u"User registered with external_auth", args[0])
            self.assertEquals(u"post_username", args[1])
            method_name, args, _kwargs = audit_log_calls[2]
            self.assertEquals(method_name, "info")
            self.assertEquals(len(args), 3)
            self.assertIn(u"Updated ExternalAuthMap for ", args[0])
            self.assertEquals(u"post_username", args[1])
            self.assertEquals(u"*****@*****.**", args[2].external_id)

            # check that the created user has the right email, either taken from shib or user input
            if mail:
                self.assertEqual(user.email, mail)
                self.assertEqual(list(User.objects.filter(email=postvars["email"])), [])
                self.assertIsNotNone(User.objects.get(email=mail))  # get enforces only 1 such user
            else:
                self.assertEqual(user.email, postvars["email"])
                self.assertEqual(list(User.objects.filter(email=mail)), [])
                self.assertIsNotNone(User.objects.get(email=postvars["email"]))  # get enforces only 1 such user

            # check that the created user profile has the right name, either taken from shib or user input
            profile = UserProfile.objects.get(user=user)
            sn_empty = not identity.get("sn")
            given_name_empty = not identity.get("givenName")
            displayname_empty = not identity.get("displayName")

            if displayname_empty:
                if sn_empty and given_name_empty:
                    self.assertEqual(profile.name, postvars["name"])
                else:
                    self.assertEqual(profile.name, request2.session["ExternalAuthMap"].external_name)
                    self.assertNotIn(u";", profile.name)
            else:
                self.assertEqual(profile.name, request2.session["ExternalAuthMap"].external_name)
                self.assertEqual(profile.name, identity.get("displayName"))

            # clean up for next loop
            request2.session["ExternalAuthMap"].delete()
            UserProfile.objects.filter(user=user).delete()
            Registration.objects.filter(user=user).delete()
            user.delete()