Exemple #1
0
 def test_do_not_send_email_and_do_activate(self):
     """
     Tests that when an inactive user logs-in using the social auth,
     an activation email is not sent.
     """
     pipeline_partial = {'kwargs': {'social': {'uid': 'fake uid'}}}
     user = UserFactory(is_active=False)
     Registration().register(user)
     request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL)
     request.user = user
     with patch(
             'common.djangoapps.student.views.management.compose_and_send_activation_email'
     ) as email:
         with patch(
                 'common.djangoapps.third_party_auth.provider.Registry.get_from_pipeline'
         ) as reg:
             with patch('common.djangoapps.third_party_auth.pipeline.get',
                        return_value=pipeline_partial):
                 with patch(
                         'common.djangoapps.third_party_auth.pipeline.running',
                         return_value=True):
                     with patch(
                             'common.djangoapps.third_party_auth.is_enabled',
                             return_value=True):
                         reg.skip_email_verification = True
                         inactive_user_view(request)
                         self.assertEqual(user.is_active, True)
                         self.assertEqual(
                             email.called,
                             False,
                             msg='method should not have been called')
Exemple #2
0
    def test_authenticated_user_cannot_activate_another_account(self):
        """
        Verify that if a user is authenticated and tries to activate another account,
        error message is shown.
        """
        # create a new user and registration link
        second_user = UserFactory.create(
            username='******',
            email='*****@*****.**',
            password='******',
            is_active=False,
        )

        registration = Registration()
        registration.register(second_user)
        registration.save()

        # Login first user
        self.login()
        # Try activating second user's account
        response = self.client.get(reverse('activate',
                                           args=[registration.activation_key]),
                                   follow=True)
        self.assertContains(response, 'Your account could not be activated')

        # verify that both users have their is_active state set to False
        self._assert_user_active_state(expected_active_state=False)
        second_user.refresh_from_db()
        assert second_user.is_active is False
    def setUp(self):
        """ Setup components used by each test."""
        super().setUp()
        self.student = UserFactory()

        registration = Registration()
        registration.register(self.student)

        self.msg = compose_activation_email("http://www.example.com", self.student, registration)
Exemple #4
0
    def setUp(self):
        """ Setup components used by each test."""
        super(SendActivationEmailTestCase, self).setUp()  # lint-amnesty, pylint: disable=super-with-arguments
        self.student = UserFactory()

        registration = Registration()
        registration.register(self.student)

        self.msg = compose_activation_email("http://www.example.com",
                                            self.student, registration)
Exemple #5
0
 def setUp(self):
     """
     Create a user, then log in.
     """
     super().setUp()
     self.user = UserFactory()
     Registration().register(self.user)
     result = self.client.login(username=self.user.username, password="******")
     assert result, 'Could not log in'
     self.path = reverse('send_account_activation_email')
Exemple #6
0
 def test_send_email_to_inactive_user(self, email):
     """
     Tests that when an inactive user logs-in using the social auth, system
     sends an activation email to the user.
     """
     inactive_user = UserFactory(is_active=False)
     Registration().register(inactive_user)
     request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL)
     request.user = inactive_user
     with patch('common.djangoapps.edxmako.request_context.get_current_request', return_value=request):
         with patch('common.djangoapps.third_party_auth.pipeline.running', return_value=False):
             inactive_user_view(request)
             assert email.called is True, 'method should have been called'
Exemple #7
0
 def test_inactive_user_view_prevents_invalid_redirect(self, mock_redirect):
     inactive_user = UserFactory(is_active=False)
     Registration().register(inactive_user)
     request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL,
                                    {'next': 'https://evil.com'})
     request.user = inactive_user
     with patch(
             'common.djangoapps.edxmako.request_context.get_current_request',
             return_value=request):
         with patch('common.djangoapps.third_party_auth.pipeline.running',
                    return_value=False):
             inactive_user_view(request)
             mock_redirect.assert_called_with('dashboard')
Exemple #8
0
    def setUp(self):
        update_email_marketing_config(enabled=False)
        self.request_factory = RequestFactory()
        self.user = UserFactory.create(username='******', email=TEST_EMAIL)
        self.registration = Registration()
        self.registration.register(self.user)

        self.request = self.request_factory.get("foo")
        update_email_marketing_config(enabled=True)

        # create some test course objects
        self.course_id_string = 'edX/toy/2012_Fall'
        self.course_id = CourseKey.from_string(self.course_id_string)
        self.course_url = 'http://testserver/courses/edX/toy/2012_Fall/info'

        self.site = Site.objects.get_current()
        self.request.site = self.site
        super(EmailMarketingTests, self).setUp()  # lint-amnesty, pylint: disable=super-with-arguments
    def setUp(self):
        super(TestActivateAccount, self).setUp()  # lint-amnesty, pylint: disable=super-with-arguments
        self.username = "******"
        self.email = "*****@*****.**"
        self.password = "******"
        self.user = UserFactory.create(
            username=self.username, email=self.email, password=self.password, is_active=False,
        )

        # Set Up Registration
        self.registration = Registration()
        self.registration.register(self.user)
        self.registration.save()

        self.platform_name = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)
        self.activation_email_support_link = configuration_helpers.get_value(
            'ACTIVATION_EMAIL_SUPPORT_LINK', settings.ACTIVATION_EMAIL_SUPPORT_LINK
        ) or settings.SUPPORT_SITE_LINK
Exemple #10
0
    def create_user(self, uname, name, password=None):
        """ Creates a user """

        if not uname:
            return _('Must provide username')
        if not name:
            return _('Must provide full name')

        msg = u''
        if not password:
            return _('Password must be supplied')

        email = uname

        if '@' not in email:
            msg += _('email address required (not username)')
            return msg
        new_password = password

        user = User(username=uname, email=email, is_active=True)
        user.set_password(new_password)
        try:
            user.save()
        except IntegrityError:
            msg += _(u'Oops, failed to create user {user}, {error}').format(
                user=user,
                error="IntegrityError"
            )
            return msg

        reg = Registration()
        reg.register(user)

        profile = UserProfile(user=user)
        profile.name = name
        profile.save()

        msg += _(u'User {user} created successfully!').format(user=user)
        return msg
Exemple #11
0
def do_create_account(form, custom_form=None):
    """
    Given cleaned post variables, create the User and UserProfile objects, as well as the
    registration for this user.

    Returns a tuple (User, UserProfile, Registration).

    Note: this function is also used for creating test users.
    """
    # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation
    if not configuration_helpers.get_value(
            'ALLOW_PUBLIC_ACCOUNT_CREATION',
            settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)):
        raise PermissionDenied()

    errors = {}
    errors.update(form.errors)
    if custom_form:
        errors.update(custom_form.errors)

    if errors:
        raise ValidationError(errors)

    proposed_username = form.cleaned_data["username"]
    user = User(username=proposed_username,
                email=form.cleaned_data["email"],
                is_active=False)
    password = normalize_password(form.cleaned_data["password"])
    user.set_password(password)
    registration = Registration()

    # TODO: Rearrange so that if part of the process fails, the whole process fails.
    # Right now, we can have e.g. no registration e-mail sent out and a zombie account
    try:
        with transaction.atomic():
            user.save()
            if custom_form:
                custom_model = custom_form.save(commit=False)
                custom_model.user = user
                custom_model.save()
    except IntegrityError:
        # Figure out the cause of the integrity error
        # TODO duplicate email is already handled by form.errors above as a ValidationError.
        # The checks for duplicate email/username should occur in the same place with an
        # AccountValidationError and a consistent user message returned (i.e. both should
        # return "It looks like {username} belongs to an existing account. Try again with a
        # different username.")
        if username_exists_or_retired(user.username):
            raise AccountValidationError(
                USERNAME_EXISTS_MSG_FMT.format(username=proposed_username),
                field="username")
        elif email_exists_or_retired(user.email):
            raise AccountValidationError(_(
                "An account with the Email '{email}' already exists.").format(
                    email=user.email),
                                         field="email")
        else:
            raise

    registration.register(user)

    profile_fields = [
        "name", "level_of_education", "gender", "mailing_address", "city",
        "country", "goals", "year_of_birth"
    ]
    profile = UserProfile(
        user=user,
        **{key: form.cleaned_data.get(key)
           for key in profile_fields})
    extended_profile = form.cleaned_extended_profile
    if extended_profile:
        profile.meta = json.dumps(extended_profile)
    try:
        profile.save()
    except Exception:
        log.exception(
            "UserProfile creation failed for user {id}.".format(id=user.id))
        raise

    return user, profile, registration
 def _create_sample_data(self):
     """
     Creates the users and register them.
     """
     for __ in range(3):
         Registration().register(UserFactory.create())