Exemple #1
0
    def test_admin_approval_email_falls_back_to_django_default_from_email(
            self):
        """
        ``SupervisedRegistrationManager.send_admin_approve_email`` sends an
        email.

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = self.registration_profile.objects.create_profile(new_user)
        profile.activated = True
        self.registration_profile.objects.send_admin_approve_email(
            new_user, Site.objects.get_current())
        self.assertEqual(mail.outbox[0].from_email, '*****@*****.**')
Exemple #2
0
    def test_expired_user_deletion_activation_window(self):
        """
        ``RegistrationProfile.objects.delete_expired_users()`` only
        deletes inactive users whose activation window has expired.

        """
        self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        expired_user = (self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(),
            username='******',
            password='******',
            email='*****@*****.**'))
        expired_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        expired_user.save()

        self.registration_profile.objects.delete_expired_users()
        self.assertEqual(self.registration_profile.objects.count(), 1)
        self.assertRaises(UserModel().DoesNotExist,
                          UserModel().objects.get,
                          username='******')
Exemple #3
0
    def test_management_command(self):
        """
        The ``cleanupregistration`` management command properly
        deletes expired accounts.

        """
        self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        expired_user = (self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(),
            username='******',
            password='******',
            email='*****@*****.**'))
        expired_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        expired_user.save()

        management.call_command('cleanupregistration')
        self.assertEqual(self.registration_profile.objects.count(), 1)
        self.assertRaises(UserModel().DoesNotExist,
                          UserModel().objects.get,
                          username='******')
Exemple #4
0
    def test_admin_approval_complete_email_is_plain_text_if_html_disabled(
            self):
        """
        ``SupervisedRegistrationProfile.send_admin_approve_complete_email``
        sends a plain text email if settings.REGISTRATION_EMAIL_HTML is False.

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = self.registration_profile.objects.create_profile(new_user)
        profile.send_admin_approve_complete_email(Site.objects.get_current())
        self.assertEqual(len(mail.outbox), 1)

        self.assertEqual(len(mail.outbox[0].alternatives), 0)
Exemple #5
0
    def test_admin_approval_not_activated(self):
        """
        Approving a non activated user's account fails
        """
        new_user = self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        profile = self.registration_profile.objects.get(user=new_user)

        user = self.registration_profile.objects.admin_approve_user(
            profile.id, Site.objects.get_current())
        self.failIf(isinstance(user, UserModel()))
        self.assertEqual(user, False)
        self.assertEqual(profile.user.is_active, False)
Exemple #6
0
    def test_admin_approval_email_is_html_by_default(self):
        """
        ``SupervisedRegistrationProfile.send_activation_email`` sends an html
        email by default.

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = self.registration_profile.objects.create_profile(new_user)
        profile.activated = True
        self.registration_profile.objects.send_admin_approve_email(
            new_user, Site.objects.get_current())

        self.assertEqual(len(mail.outbox[0].alternatives), 1)
Exemple #7
0
    def test_expired_activation(self):
        """
        Attempting to activate outside the permitted window does not
        activate the account.

        """
        new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        new_user.save()

        profile = RegistrationProfile.objects.get(user=new_user)
        activated = RegistrationProfile.objects.activate_user(profile.activation_key)

        self.failIf(isinstance(activated, UserModel()))
        self.failIf(activated)

        new_user = UserModel().objects.get(username='******')
        self.failIf(new_user.is_active)

        profile = RegistrationProfile.objects.get(user=new_user)
        self.assertNotEqual(profile.activation_key, RegistrationProfile.ACTIVATED)
Exemple #8
0
    def test_profile_creation(self):
        """
        Creating a registration profile for a user populates the
        profile with the correct user and a SHA256 hash to use as
        activation key.

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = self.registration_profile.objects.create_profile(new_user)

        self.assertEqual(self.registration_profile.objects.count(), 1)
        self.assertEqual(profile.user.id, new_user.id)
        self.assertTrue(re.match('^[a-f0-9]{40,64}$', profile.activation_key))
        self.assertEqual(str(profile), "Registration information for alice")
Exemple #9
0
    def test_registered_users_can_add_friends_and_accept_friend_requests(self):

        # Sally is back and she's so excited because her best friend Jo Smo has
        # just joined TSN
        jo = UserModel().objects.create_user(username='******',
                                             first_name='Jo',
                                             last_name='Smo',
                                             password='******',
                                             email='*****@*****.**')
        UserProfile.objects.create(user=jo, birthday='1985-03-15', gender='M')
        self.login('sally', 'sallyiscooler')

        # Sally decides goes to view her friends and realizes that she doesn't
        # have any :(
        self.browser.find_element_by_id('my_friends').click()
        self.assertIn("doesn't have any friends", self.browser.page_source)

        # To remedy this, she goes to the find friend page to find Jo
        self.browser.find_element_by_id('find_friends').click()
        self.browser.find_element_by_name('query').send_keys('jo smo\n')

        # Jo Smo appears in her results and she clicks the button to add him
        # as a friend
        self.assertIn(
            'Jo Smo',
            self.browser.find_element_by_class_name('media-heading').text)
        self.browser.find_element_by_class_name('btn-success').click()

        # The button now reads 'Cancel Request' and is yellow
        self.assertIn('Cancel Request', self.browser.page_source)
        self.assertIn('btn-warning', self.browser.page_source)

        # Since Sally and Jo share a computer Sally logs out and Jo logs in
        self.browser.find_element_by_id('logout').click()
        self.login('josmo', 'josmoyouknow')

        # Jo notices that he has a notification and clicks on the link
        notifications = self.browser.find_element_by_id('my_notifications')
        self.assertIn('1', notifications.text)
        notifications.click()

        # He clicks on the notification on the page and accepts the request
        self.browser.find_element_by_class_name('panel-heading').click()
        self.browser.find_element_by_class_name('btn-success').click()

        # Jo then goes to his friends and sees Sally is one of them
        self.browser.find_element_by_id('my_friends').click()
        self.assertIn(
            'Sally Hayes',
            self.browser.find_element_by_class_name('media-heading').text)
Exemple #10
0
    def delete_expired_users(self):
        """
        Remove expired instances of ``RegistrationProfile`` and their
        associated ``User``s.

        Accounts to be deleted are identified by searching for
        instances of ``RegistrationProfile`` with expired activation
        keys, and then checking to see if their associated ``User``
        instances have the field ``is_active`` set to ``False``; any
        ``User`` who is both inactive and has an expired activation
        key will be deleted.

        It is recommended that this method be executed regularly as
        part of your routine site maintenance; this application
        provides a custom management command which will call this
        method, accessible as ``manage.py cleanupregistration``.

        Regularly clearing out accounts which have never been
        activated serves two useful purposes:

        1. It alleviates the ocasional need to reset a
           ``RegistrationProfile`` and/or re-send an activation email
           when a user does not receive or does not act upon the
           initial activation email; since the account will be
           deleted, the user will be able to simply re-register and
           receive a new activation key.

        2. It prevents the possibility of a malicious user registering
           one or more accounts and never activating them (thus
           denying the use of those usernames to anyone else); since
           those accounts will be deleted, the usernames will become
           available for use again.

        If you have a troublesome ``User`` and wish to disable their
        account while keeping it in the database, simply delete the
        associated ``RegistrationProfile``; an inactive ``User`` which
        does not have an associated ``RegistrationProfile`` will not
        be deleted.

        """
        for profile in self.all():
            try:
                if profile.activation_key_expired():
                    user = profile.user
                    if not user.is_active:
                        user.delete()
                        profile.delete()
            except UserModel().DoesNotExist:
                profile.delete()
Exemple #11
0
    def test_admin_approval_email(self):
        """
        ``SupervisedRegistrationManager.send_admin_approve_email`` sends an
        email to the site administrators

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = self.registration_profile.objects.create_profile(new_user)
        profile.activated = True
        self.registration_profile.objects.send_admin_approve_email(
            new_user, Site.objects.get_current())
        self.assertEqual(len(mail.outbox), 1)
        admins_emails = [value[1] for value in settings.REGISTRATION_ADMINS]
        for email in mail.outbox[0].to:
            self.assertIn(email, admins_emails)
 def test_registration_exception(self, create_inactive_user):
     """
     User is not created beforehand if an exception occurred at
     creating registration profile.
     """
     create_inactive_user.side_effect = DatabaseError()
     valid_data = {
         'username': '******',
         'email': '*****@*****.**',
         'password1': 'secret',
         'password2': 'secret'
     }
     with self.assertRaises(DatabaseError):
         self.client.post(reverse('registration_register'), data=valid_data)
     assert not UserModel().objects.filter(username='******').exists()
 def setUp(self):
     self.browser = webdriver.Firefox()
     self.browser.implicitly_wait(3)
     self.browser.wait = WebDriverWait(self.browser, 10)
     sally = UserModel().objects.create_user(
         first_name='Sally',
         last_name='Hayes',
         username='******',
         email='[email protected]:8081',
         password='******'
     )
     sally_profile = UserProfile()
     sally_profile.user = sally
     sally_profile.birthday = '1985-07-22'
     sally_profile.gender = 'F'
     sally_profile.save()
Exemple #14
0
    def register(self, request, **cleaned_data):
        username, email, password = cleaned_data['username'], cleaned_data[
            'email'], cleaned_data['password1']
        UserModel().objects.create_user(username, email, password)

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        UserProfile.objects.create(user=new_user,
                                   website=cleaned_data['website'],
                                   picture=cleaned_data['picture'])
        # else:
        #     UserProfile.objects.create(user=new_user,website=cleaned_data['website'])
        return new_user
Exemple #15
0
    def test_registration_form(self):
        """
        Test that ``RegistrationForm`` enforces username constraints
        and matching passwords.

        """
        # Create a user so we can verify that duplicate usernames aren't
        # permitted.
        UserModel().objects.create_user('alice', '*****@*****.**', 'secret')

        bad_username_error = 'This value may contain only letters, numbers and @/./+/-/_ characters.'
        if DJANGO_VERSION >= StrictVersion('1.8'):
            bad_username_error = 'Enter a valid username. ' + bad_username_error

        invalid_data_dicts = [
            # Non-alphanumeric username.
            {'data': {'username': '******',
                      'email': '*****@*****.**',
                      'password1': 'foo',
                      'password2': 'foo'},
            'error': ('username', [bad_username_error])},
            # Already-existing username.
            {'data': {'username': '******',
                      'email': '*****@*****.**',
                      'password1': 'secret',
                      'password2': 'secret'},
            'error': ('username', ["A user with that username already exists."])},
            # Mismatched passwords.
            {'data': {'username': '******',
                      'email': '*****@*****.**',
                      'password1': 'foo',
                      'password2': 'bar'},
            'error': ('password2', ["The two password fields didn't match."])},
            ]

        for invalid_dict in invalid_data_dicts:
            form = forms.RegistrationForm(data=invalid_dict['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[invalid_dict['error'][0]],
                             invalid_dict['error'][1])

        form = forms.RegistrationForm(data={'username': '******',
                                            'email': '*****@*****.**',
                                            'password1': 'foo',
                                            'password2': 'foo'})
        self.failUnless(form.is_valid())
Exemple #16
0
    def test_valid_activation(self):
        """
        Activating a user within the permitted window makes the
        account active, and resets the activation key.

        """
        new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        profile = RegistrationProfile.objects.get(user=new_user)
        activated = RegistrationProfile.objects.activate_user(profile.activation_key)

        self.failUnless(isinstance(activated, UserModel()))
        self.assertEqual(activated.id, new_user.id)
        self.failUnless(activated.is_active)

        profile = RegistrationProfile.objects.get(user=new_user)
        self.assertEqual(profile.activation_key, RegistrationProfile.ACTIVATED)
Exemple #17
0
    def register(self, request, **cleaned_data):
        # Create a new User
        username, email, password = cleaned_data['username'], cleaned_data[
            'email'], cleaned_data['password1']
        new_user_object = UserModel().objects.create_user(
            username, email, password)

        # And links that user to a new (empty) UserProfile
        profile = UserProfile(user=new_user_object)
        profile.save()

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Exemple #18
0
    def test_resend_activation_email(self):
        """
        Test the admin custom command 'resend activation email'
        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = RegistrationProfile.objects.create_profile(new_user)

        registrationprofile_list = reverse(
            'admin:registration_registrationprofile_changelist')
        post_data = {
            'action': 'resend_activation_email',
            helpers.ACTION_CHECKBOX_NAME: [profile.pk],
        }
        self.client.post(registrationprofile_list, post_data, follow=True)

        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
Exemple #19
0
    def register(self, request, form):
        """
        Given a username, email address and password, register a new
        user account, which will initially be inactive.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)

        if hasattr(form, 'save'):
            new_user_instance = form.save()
        else:
            new_user_instance = UserModel().objects.create_user(
                **form.cleaned_data)

        new_user = RegistrationProfile.objects.create_inactive_user(
            new_user=new_user_instance,
            site=site,
            send_email=self.SEND_ACTIVATION_EMAIL,
            request=request,
        )
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Exemple #20
0
 def clean(self):
     email = self.cleaned_data['email']
     email_domain = email.split('@')[1]
     email_group = email.split('@')[0].split('.')[-1]
     group = self.cleaned_data['group']
     if UserModel().objects.filter(email__iexact=self.cleaned_data['email']):
         raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
     if group == 'faculty':
         if email_group == 'faculty' and email_domain in ['iitbhu.ac.in', 'itbhu.ac.in']:
             pass
         else:
             raise forms.ValidationError(_("Registration in IIT BHU Faculty group only allowed for IIT BHU faculty."))
     elif group == 'iitbhustudent':
         if email_domain not in ['iitbhu.ac.in', 'itbhu.ac.in']:
             raise forms.ValidationError(_("Registration in IIT BHU Student group only allowed for iitbhu domains."))
         else:
             pass
     return self.cleaned_data
Exemple #21
0
    def test_valid_activation(self):
        """
        Activating a user within the permitted window makes the
        account active, and resets the activation key.

        """
        new_user = self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        profile = self.registration_profile.objects.get(user=new_user)
        user, activated = self.registration_profile.objects.activate_user(
            profile.activation_key, Site.objects.get_current())

        self.assertIsInstance(user, UserModel())
        self.assertEqual(user.id, new_user.id)
        self.assertFalse(user.is_active)
        self.assertTrue(activated)

        profile = self.registration_profile.objects.get(user=new_user)
        self.assertTrue(profile.activated)
Exemple #22
0
    def test_manually_registered_account(self):
        """
        Test if a user failed to go through the registration flow but was
        manually marked ``is_active`` in the DB.  Although the profile is
        expired and not active, we should never delete active users.
        """
        active_user = (self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(),
            username='******',
            password='******',
            email='*****@*****.**'))
        active_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        active_user.is_active = True
        active_user.save()

        self.registration_profile.objects.delete_expired_users()
        self.assertEqual(self.registration_profile.objects.count(), 1)
        self.assertEqual(UserModel().objects.get(username='******'), active_user)
Exemple #23
0
    def test_activate_users(self):
        """
        Test the admin custom command 'activate users'

        """
        new_user = UserModel().objects.create_user(**self.user_info)
        profile = RegistrationProfile.objects.create_profile(new_user)

        self.assertFalse(profile.activated)

        registrationprofile_list = reverse(
            'admin:registration_registrationprofile_changelist')
        post_data = {
            'action': 'activate_users',
            helpers.ACTION_CHECKBOX_NAME: [profile.pk],
        }
        self.client.post(registrationprofile_list, post_data, follow=True)

        profile = RegistrationProfile.objects.get(user=new_user)
        self.assertTrue(profile.activated)
    def create_inactive_user(self, username, email, password,
                             site, send_email=True):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new
        user. To disable this, pass ``send_email=False``.

        """
        new_user = UserModel().objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()

        registration_profile = self.create_profile(new_user)

        if send_email:
            registration_profile.send_activation_email(site)

        return new_user
    def test_registration_no_email(self):
        """
        Overriden Registration view does not send an activation email if the
        associated class variable is set to ``False``

        """
        class RegistrationNoEmailView(RegistrationView):
            SEND_ACTIVATION_EMAIL = False

        request_factory = RequestFactory()
        view = RegistrationNoEmailView.as_view()
        resp = view(request_factory.post('/', data={
            'username': '******',
            'email': '*****@*****.**',
            'password1': 'secret',
            'password2': 'secret'}))

        new_user = UserModel().objects.get(username='******')
        # A registration profile was created, and no activation email was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 0)
Exemple #26
0
    def test_registration_form_unique_email(self):
        """
        Test that ``RegistrationFormUniqueEmail`` validates uniqueness
        of email addresses.

        """
        # Create a user so we can verify that duplicate addresses
        # aren't permitted.
        UserModel().objects.create_user('alice', '*****@*****.**', 'secret')

        form = forms.RegistrationFormUniqueEmail(data={'username': '******',
                                                       'email': '*****@*****.**',
                                                       'password1': 'foo',
                                                       'password2': 'foo'})
        self.failIf(form.is_valid())
        self.assertEqual(form.errors['email'],
                         ["This email address is already in use. Please supply a different email address."])

        form = forms.RegistrationFormUniqueEmail(data={'username': '******',
                                                       'email': '*****@*****.**',
                                                       'password1': 'foo',
                                                       'password2': 'foo'})
        self.failUnless(form.is_valid())
Exemple #27
0
    def create_inactive_user(self, username, email, password,
                             site, send_email=True, request=None):
        """
        Create a new, inactive ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.

        By default, an activation email will be sent to the new
        user. To disable this, pass ``send_email=False``.
        Additionally, if email is sent and ``request`` is supplied,
        it will be passed to the email template.

        """
        new_user = UserModel().objects.create_user(username, email, password)
        new_user.is_active = False
        new_user.save()

        registration_profile = self.create_profile(new_user)

        if send_email:
            registration_profile.send_activation_email(site, request)

        return new_user
    def test_registration_no_sites(self):
        """
        Registration still functions properly when
        ``django.contrib.sites`` is not installed; the fallback will
        be a ``RequestSite`` instance.

        """
        resp = self.client.post(reverse('registration_register'),
                                data={'username': '******',
                                      'email': '*****@*****.**',
                                      'password1': 'secret',
                                      'password2': 'secret'})
        self.assertEqual(302, resp.status_code)

        new_user = UserModel().objects.get(username='******')

        self.assertTrue(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        self.assertFalse(new_user.is_active)

        self.assertEqual(self.registration_profile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)
Exemple #29
0
    def test_registration(self):
        """
        Registration creates a new account and logs the user in.

        """
        resp = self.client.post(reverse('registration_register'),
                                data={'username': '******',
                                      'email': '*****@*****.**',
                                      'password1': 'secret',
                                      'password2': 'secret'})
        new_user = UserModel().objects.get(username='******')
        self.assertEqual(302, resp.status_code)
        self.failUnless(reverse('registration_complete') in resp['Location'])

        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        # New user must be active.
        self.failUnless(new_user.is_active)

        # New user must be logged in.
        resp = self.client.get(reverse('registration_register'))
        self.failUnless(resp.context['user'].is_authenticated())
Exemple #30
0
    def test_activation_key_backwards_compatibility(self):
        """
        Make sure that users created with the old create_new_activation_key
        method can still be activated.
        """
        current_method = self.registration_profile.create_new_activation_key

        def old_method(self, save=True):
            salt = hashlib.sha1(
                six.text_type(random.random()).encode('ascii')
            ).hexdigest()[:5]
            salt = salt.encode('ascii')
            user_pk = str(self.user.pk)
            if isinstance(user_pk, six.text_type):
                user_pk = user_pk.encode('utf-8')
            self.activation_key = hashlib.sha1(salt + user_pk).hexdigest()
            if save:
                self.save()
            return self.activation_key

        self.registration_profile.create_new_activation_key = old_method

        new_user = self.registration_profile.objects.create_inactive_user(
            site=Site.objects.get_current(), **self.user_info)
        profile = self.registration_profile.objects.get(user=new_user)

        self.registration_profile.create_new_activation_key = current_method
        user, activated = self.registration_profile.objects.activate_user(
            profile.activation_key, Site.objects.get_current())

        self.assertIsInstance(user, UserModel())
        self.assertEqual(user.id, new_user.id)
        self.assertTrue(user.is_active)
        self.assertTrue(activated)

        profile = self.registration_profile.objects.get(user=new_user)
        self.assertTrue(profile.activated)