Ejemplo n.º 1
0
    def save(self):
        """ Generate a random username before falling back to parent signup form """
        while True:
            username = sha_constructor(str(random.random())).hexdigest()[:5]
            try:
                get_user_model().objects.get(username__iexact=username)
            except get_user_model().DoesNotExist: break

        self.cleaned_data['username'] = username
        return super(SignupFormOnlyEmail, self).save()
Ejemplo n.º 2
0
    def __init__(self, user, *args, **kwargs):
        """
        The current ``user`` is needed for initialisation of this form so
        that we can check if the email address is still free and not always
        returning ``True`` for this query because it's the users own e-mail
        address.

        """
        super(ChangeEmailForm, self).__init__(*args, **kwargs)
        if not isinstance(user, get_user_model()):
            raise TypeError, "user must be an instance of %s" % get_user_model().__name__
        else: self.user = user
Ejemplo n.º 3
0
    def check_permissions(self):
        """
        Checks that all permissions are set correctly for the users.

        :return: A set of users whose permissions was wrong.

        """
        # Variable to supply some feedback
        changed_permissions = []
        changed_users = []
        warnings = []

        # Check that all the permissions are available.
        for model, perms in ASSIGNED_PERMISSIONS.items():
            if model == 'profile':
                model_obj = get_profile_model()
            else: model_obj = get_user_model()

            model_content_type = ContentType.objects.get_for_model(model_obj)

            for perm in perms:
                try:
                    Permission.objects.get(codename=perm[0],
                                           content_type=model_content_type)
                except Permission.DoesNotExist:
                    changed_permissions.append(perm[1])
                    Permission.objects.create(name=perm[1],
                                              codename=perm[0],
                                              content_type=model_content_type)

        # it is safe to rely on settings.ANONYMOUS_USER_ID since it is a
        # requirement of django-guardian
        for user in get_user_model().objects.exclude(id=settings.ANONYMOUS_USER_ID):
            try:
                user_profile = user.get_profile()
            except ObjectDoesNotExist:
                warnings.append(_("No profile found for %(username)s") \
                                    % {'username': user.username})
            else:
                all_permissions = get_perms(user, user_profile) + get_perms(user, user)

                for model, perms in ASSIGNED_PERMISSIONS.items():
                    if model == 'profile':
                        perm_object = user.get_profile()
                    else: perm_object = user

                    for perm in perms:
                        if perm[0] not in all_permissions:
                            assign(perm[0], user, perm_object)
                            changed_users.append(user)

        return (changed_permissions, changed_users, warnings)
Ejemplo n.º 4
0
 def clean_email(self):
     """ Validate that the e-mail address is unique. """
     if get_user_model().objects.filter(email__iexact=self.cleaned_data['email']):
         if UserenaSignup.objects.filter(user__email__iexact=self.cleaned_data['email']).exclude(activation_key=userena_settings.USERENA_ACTIVATED):
             raise forms.ValidationError(_('This email is already in use but not confirmed. Please check you email for verification steps.'))
         raise forms.ValidationError(_('This email is already in use. Please supply a different email.'))
     return self.cleaned_data['email']
Ejemplo n.º 5
0
 def clean_email(self):
     """ Validate that the email is not already registered with another user """
     if self.cleaned_data['email'].lower() == self.user.email:
         raise forms.ValidationError(_(u'You\'re already known under this email.'))
     if get_user_model().objects.filter(email__iexact=self.cleaned_data['email']).exclude(email__iexact=self.user.email):
         raise forms.ValidationError(_(u'This email is already in use. Please supply a different email.'))
     return self.cleaned_data['email']
Ejemplo n.º 6
0
    def authenticate(self, identification, password=None, check_password=True):
        """
        Authenticates a user through the combination email/username with
        password.

        :param identification:
            A string containing the username or e-mail of the user that is
            trying to authenticate.

        :password:
            Optional string containing the password for the user.

        :param check_password:
            Boolean that defines if the password should be checked for this
            user.  Always keep this ``True``. This is only used by userena at
            activation when a user opens a page with a secret hash.

        :return: The signed in :class:`User`.

        """
        User = get_user_model()
        if email_re.search(identification):
            try: user = User.objects.get(email__iexact=identification)
            except User.DoesNotExist: return None
        else:
            try: user = User.objects.get(username__iexact=identification)
            except User.DoesNotExist: return None
        if check_password:
            if user.check_password(password):
                return user
            return None
        else: return user
Ejemplo n.º 7
0
    def clean_username(self):
        """
        Validate that the username is alphanumeric and is not already in use.
        Also validates that the username is not listed in
        ``USERENA_FORBIDDEN_USERNAMES`` list.

        """
        try:
            user = get_user_model().objects.get(username__iexact=self.cleaned_data['username'])
        except get_user_model().DoesNotExist:
            pass
        else:
            if UserenaSignup.objects.filter(user__username__iexact=self.cleaned_data['username']).exclude(activation_key=userena_settings.USERENA_ACTIVATED):
                raise forms.ValidationError(_('This username is already taken but not confirmed. Please check you email for verification steps.'))
            raise forms.ValidationError(_('This username is already taken.'))
        if self.cleaned_data['username'].lower() in userena_settings.USERENA_FORBIDDEN_USERNAMES:
            raise forms.ValidationError(_('This username is not allowed.'))
        return self.cleaned_data['username']
Ejemplo n.º 8
0
    def create_user(self, username, email, password, active=False,
                    send_email=True):
        """
        A simple wrapper that creates a new :class:`User`.

        :param username:
            String containing the username of the new user.

        :param email:
            String containing the email address of the new user.

        :param password:
            String containing the password for the new user.

        :param active:
            Boolean that defines if the user requires activation by clicking
            on a link in an e-mail. Defaults to ``False``.

        :param send_email:
            Boolean that defines if the user should be sent an email. You could
            set this to ``False`` when you want to create a user in your own
            code, but don't want the user to activate through email.

        :return: :class:`User` instance representing the new user.

        """
        now = get_datetime_now()

        new_user = get_user_model().objects.create_user(
            username, email, password)
        new_user.is_active = active
        new_user.save()

        userena_profile = self.create_userena_profile(new_user)

        # All users have an empty profile
        profile_model = get_profile_model()
        try:
            new_profile = new_user.get_profile()
        except profile_model.DoesNotExist:
            new_profile = profile_model(user=new_user)
            new_profile.save(using=self._db)

        # Give permissions to view and change profile
        for perm in ASSIGNED_PERMISSIONS['profile']:
            assign(perm[0], new_user, new_profile)

        # Give permissions to view and change itself
        for perm in ASSIGNED_PERMISSIONS['user']:
            assign(perm[0], new_user, new_user)

        if send_email:
            userena_profile.send_activation_email()

        return new_user
Ejemplo n.º 9
0
    def delete_expired_users(self):
        """
        Checks for expired users and delete's the ``User`` associated with
        it. Skips if the user ``is_staff``.

        :return: A list containing the deleted users.

        """
        deleted_users = []
        for user in get_user_model().objects.filter(is_staff=False,
                                                    is_active=False):
            if user.userena_signup.activation_key_expired():
                deleted_users.append(user)
                user.delete()
        return deleted_users
Ejemplo n.º 10
0
    def test_signin_redirect(self):
        """
        Test redirect function which should redirect the user after a
        succesfull signin.

        """
        # Test with a requested redirect
        self.failUnlessEqual(signin_redirect(redirect='/accounts/'), '/accounts/')

        # Test with only the user specified
        user = get_user_model().objects.get(pk=1)
        self.failUnlessEqual(signin_redirect(user=user),
                             '/accounts/%s/' % user.username)

        # The ultimate fallback, probably never used
        self.failUnlessEqual(signin_redirect(), settings.LOGIN_REDIRECT_URL)
Ejemplo n.º 11
0
    def can_view_profile(self, user):
        """
        Can the :class:`User` view this profile?

        Returns a boolean if a user has the rights to view the profile of this
        user.

        Users are divided into four groups:

            ``Open``
                Everyone can view your profile

            ``Closed``
                Nobody can view your profile.

            ``Registered``
                Users that are registered on the website and signed
                in only.

            ``Admin``
                Special cases like superadmin and the owner of the profile.

        Through the ``privacy`` field a owner of an profile can define what
        they want to show to whom.

        :param user:
            A Django :class:`User` instance.

        """
        # Simple cases first, we don't want to waste CPU and DB hits.
        # Everyone.
        if self.privacy == 'open':
            return True
        # Registered users.
        elif self.privacy == 'registered' \
        and isinstance(user, get_user_model()):
            return True

        # Checks done by guardian for owner and admins.
        elif 'view_profile' in get_perms(user, self):
            return True

        # Fallback to closed profile.
        return False
Ejemplo n.º 12
0
    def test_change_email_form(self):
        user = get_user_model().objects.get(pk=1)
        invalid_data_dicts = [
            # No change in e-mail address
            {'data': {'email': '*****@*****.**'},
             'error': ('email', [u'You\'re already known under this email.'])},
            # An e-mail address used by another
            {'data': {'email': '*****@*****.**'},
             'error': ('email', [u'This email is already in use. Please supply a different email.'])},
        ]
        for invalid_dict in invalid_data_dicts:
            form = forms.ChangeEmailForm(user, data=invalid_dict['data'])
            self.failIf(form.is_valid())
            self.assertEqual(form.errors[invalid_dict['error'][0]],
                             invalid_dict['error'][1])

        # Test a valid post
        form = forms.ChangeEmailForm(user,
                                     data={'email': '*****@*****.**'})
        self.failUnless(form.is_valid())
Ejemplo n.º 13
0
    def test_save_msg(self):
        """ Test valid data """
        valid_data = {'to': 'john, jane',
                      'body': 'Body'}

        form = ComposeForm(data=valid_data)

        self.failUnless(form.is_valid())

        # Save the form.
        sender = get_user_model().objects.get(username='******')
        msg = form.save(sender)

        # Check if the values are set correctly
        self.failUnlessEqual(msg.body, valid_data['body'])
        self.failUnlessEqual(msg.sender, sender)
        self.failUnless(msg.sent_at)

        # Check recipients
        self.failUnlessEqual(msg.recipients.all()[0].username, 'jane')
        self.failUnlessEqual(msg.recipients.all()[1].username, 'john')
Ejemplo n.º 14
0
    def clean(self, value):
        super(CommaSeparatedUserField, self).clean(value)

        names = set(value.split(','))
        names_set = set([name.strip() for name in names])
        users = list(get_user_model().objects.filter(username__in=names_set))

        # Check for unknown names.
        unknown_names = names_set ^ set([user.username for user in users])

        recipient_filter = self._recipient_filter
        invalid_users = []
        if recipient_filter is not None:
            for r in users:
                if recipient_filter(r) is False:
                    users.remove(r)
                    invalid_users.append(r.username)

        if unknown_names or invalid_users:
            humanized_usernames = ', '.join(list(unknown_names) + invalid_users)
            raise forms.ValidationError(_("The following usernames are incorrect: %(users)s.") % {'users': humanized_usernames})

        return users
Ejemplo n.º 15
0
 def get_user(self, user_id):
     User = get_user_model()
     try: return User.objects.get(pk=user_id)
     except User.DoesNotExist:
         return None
Ejemplo n.º 16
0
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.conf import settings

from apps.userena.contrib.umessages.forms import ComposeForm
from apps.userena.contrib.umessages.models import Message, MessageRecipient
from apps.userena.utils import get_user_model

User = get_user_model()


class MessagesViewsTests(TestCase):
    fixtures = ["users", "messages"]

    def _test_login(self, named_url, **kwargs):
        """ Test that the view requires login """
        response = self.client.get(reverse(named_url, **kwargs))
        self.assertEqual(response.status_code, 302)

    def test_compose(self):
        """ A ``GET`` to the compose view """
        # Login is required.
        self._test_login("userena_umessages_compose")

        # Sign in
        client = self.client.login(username="******", password="******")
        response = self.client.get(reverse("userena_umessages_compose"))

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "umessages/message_form.html")
Ejemplo n.º 17
0
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext as _
from guardian.admin import GuardedModelAdmin

from apps.userena.models import UserenaSignup
from apps.userena.utils import get_profile_model, get_user_model

class UserenaSignupInline(admin.StackedInline):
    model = UserenaSignup
    max_num = 1

class UserenaAdmin(UserAdmin, GuardedModelAdmin):
    inlines = [UserenaSignupInline, ]
    list_display = ('username', 'email', 'first_name', 'last_name',
                    'is_staff', 'is_active', 'date_joined')
    list_filter = ('is_staff', 'is_superuser', 'is_active')

admin.site.unregister(get_user_model())
admin.site.register(get_user_model(), UserenaAdmin)
admin.site.register(get_profile_model())