Esempio n. 1
0
 def save(self, commit=True):
     self.user.set_password(self.cleaned_data['password1'])
     if commit:
         get_user_model()._default_manager.filter(pk=self.user.pk).update(
             password=self.user.password,
         )
     return self.user
Esempio n. 2
0
    def test_recover(self):
        self.user = create_user()
        url = reverse('password_reset_recover')
        response = self.client.get(url)
        User = get_user_model()

        if User is CustomUser:
            self.assertContains(response, 'Email')
        else:
            self.assertContains(response, 'Username or Email')

        response = self.client.post(url,
                                    {'username_or_email': '*****@*****.**'})
        self.assertContains(response, "Sorry, this user")

        self.assertEqual(len(mail.outbox), 0)

        if User is CustomUser:
            value = '*****@*****.**'
        else:
            value = 'foo'
        response = self.client.post(url, {'username_or_email': value},
                                    follow=True)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, '*****@*****.**')

        self.assertEqual(len(mail.outbox), 1)

        message = mail.outbox[0]

        self.assertEqual(message.subject,
                         u'Password recovery on testserver')

        if User is CustomUser:
            self.assertTrue('Dear [email protected],' in message.body)
        else:
            self.assertTrue('Dear foo,' in message.body)

        url = message.body.split('http://testserver')[1].split('\n', 1)[0]

        response = self.client.get(url)
        self.assertContains(response, 'New password (confirm)')
        if User is CustomUser:
            self.assertContains(response,
                                'Hi, <strong>[email protected]</strong>')
        else:
            self.assertContains(response, 'Hi, <strong>foo</strong>')

        data = {'password1': 'foo',
                'password2': 'foo'}
        response = self.client.post(url, data, follow=True)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response,
                            "Your password has successfully been reset.")

        self.assertTrue(
            get_user_model()._default_manager.get().check_password('foo'))
Esempio n. 3
0
def create_user():
    email = '*****@*****.**'
    password = '******'
    username = '******'
    model = get_user_model()
    kwargs = {}
    args = username, email, password
    if model is CustomUser:
        args = email, timezone.now(), password
    elif model is ExtensionUser:
        kwargs = {'date_of_birth': timezone.now()}
    return get_user_model()._default_manager.create_user(*args, **kwargs)
Esempio n. 4
0
    def test_form_commit(self):
        user = create_user()
        old_sha = user.password

        form = PasswordResetForm(user=user, data={'password1': 'foo',
                                                  'password2': 'foo'})
        self.assertTrue(form.is_valid())
        user = form.save(commit=False)
        self.assertEqual(get_user_model()._default_manager.get().password,
                         old_sha)
        self.assertNotEqual(old_sha, user.password)
        user.save()
        self.assertEqual(get_user_model()._default_manager.get().password,
                         user.password)
Esempio n. 5
0
    def test_insensitive_recover(self):
        self.user = create_user()
        url = reverse('insensitive_recover')
        response = self.client.get(url)
        normalized = '<strong>[email protected]</strong>'

        User = get_user_model()
        if User is CustomUser:
            self.assertContains(response, 'Email')
        else:
            self.assertContains(response, 'Username or Email')
        self.assertEqual(len(mail.outbox), 0)

        value = '*****@*****.**' if User is CustomUser else 'FOO'
        response = self.client.post(url, {'username_or_email': value},
                                    follow=True)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, normalized)

        response = self.client.post(
            url, {'username_or_email': '*****@*****.**'}, follow=True,
        )
        self.assertEqual(len(mail.outbox), 2)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, normalized)

        response = self.client.post(
            url, {'username_or_email': '*****@*****.**'}, follow=True,
        )
        self.assertEqual(len(mail.outbox), 3)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, normalized)
Esempio n. 6
0
    def __init__(self, *args, **kwargs):
        self.case_sensitive = kwargs.pop('case_sensitive', True)
        search_fields = kwargs.pop('search_fields', ('username', 'email'))
        super(PasswordRecoveryForm, self).__init__(*args, **kwargs)

        message = ("No other fields than username and email are supported "
                   "by default")
        if len(search_fields) not in (1, 2):
            raise ValueError(message)
        for field in search_fields:
            if field not in ['username', 'email']:
                raise ValueError(message)

        labels = {
            'username': _('نام کاربری'),
            'email': _('ایمیل'),
            'both': _('نام کاربری یا ایمیل'),
        }
        User = get_user_model()  # noqa
        if getattr(User, 'USERNAME_FIELD', 'username') == 'email':
            self.label_key = 'email'
        elif len(search_fields) == 1:
            self.label_key = search_fields[0]
        else:
            self.label_key = 'both'
        self.fields['username_or_email'].label = labels[self.label_key]
Esempio n. 7
0
 def get_user_by_username(self, username):
     key = 'username__%sexact' % ('' if self.case_sensitive else 'i')
     User = get_user_model()
     try:
         user = User._default_manager.get(**{key: username})
     except User.DoesNotExist:
         raise forms.ValidationError(_("این کاربر وجود ندارد"))
     return user
Esempio n. 8
0
 def get_user_by_email(self, email):
     validate_email(email)
     key = 'email__%sexact' % ('' if self.case_sensitive else 'i')
     User = get_user_model()
     try:
         user = User._default_manager.get(**{key: email})
     except User.DoesNotExist:
         raise forms.ValidationError(_("این کاربر وجود ندارد"))
     return user
Esempio n. 9
0
 def get_user_by_both(self, username):
     key = '__%sexact'
     key = key % '' if self.case_sensitive else key % 'i'
     f = lambda field: Q(**{field + key: username})
     filters = f('username') | f('email')
     User = get_user_model()
     try:
         user = User._default_manager.get(filters)
     except User.DoesNotExist:
         raise forms.ValidationError(_("این کاربر وجود ندارد"))
     except User.MultipleObjectsReturned:
         raise forms.ValidationError(_("کاربر یافت نشد"))
     return user
Esempio n. 10
0
    def test_username_input(self):
        User = get_user_model()
        if User is CustomUser:
            raise SkipTest('No username field')

        form = PasswordRecoveryForm()
        self.assertFalse(form.is_valid())

        form = PasswordRecoveryForm(data={'username_or_email': 'inexisting'})
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['username_or_email'],
                         ["Sorry, this user doesn't exist."])

        create_user()

        form = PasswordRecoveryForm(data={
            'username_or_email': 'foo',
        })
        self.assertTrue(form.is_valid())

        form = PasswordRecoveryForm(data={
            'username_or_email': 'FOO',
        })
        self.assertFalse(form.is_valid())

        form = PasswordRecoveryForm(data={
            'username_or_email': 'FOO',
        }, case_sensitive=False)
        self.assertTrue(form.is_valid())

        form = PasswordRecoveryForm(data={
            'username_or_email': '*****@*****.**',
        })
        self.assertTrue(form.is_valid())

        form = PasswordRecoveryForm(data={
            'username_or_email': '*****@*****.**',
        })
        self.assertFalse(form.is_valid())

        form = PasswordRecoveryForm(data={
            'username_or_email': '*****@*****.**',
        }, case_sensitive=False)
        self.assertTrue(form.is_valid())
Esempio n. 11
0
    def test_username_recover(self):
        if get_user_model() is CustomUser:
            raise SkipTest("No username field")
        self.user = create_user()
        url = reverse('username_recover')
        response = self.client.get(url)

        self.assertNotContains(response, "Username or Email")
        self.assertContains(response, "Username:"******"Sorry, this user")

        self.assertEqual(len(mail.outbox), 0)
        response = self.client.post(
            url, {'username_or_email': 'foo'}, follow=True,
        )
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, 'foo')
Esempio n. 12
0
    def test_content_redirection(self):
        self.user = create_user()
        url = reverse('email_recover')
        response = self.client.get(url)

        response = self.client.post(
            url, {'username_or_email': '*****@*****.**'}, follow=True,
        )
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, '<strong>[email protected]</strong>')

        if get_user_model() is CustomUser:
            return  # no username field

        url = reverse('username_recover')
        response = self.client.post(
            url, {'username_or_email': 'foo'}, follow=True,
        )
        self.assertEqual(len(mail.outbox), 2)
        self.assertEqual(len(response.redirect_chain), 1)
        self.assertContains(response, '<strong>foo</strong>')