示例#1
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 = get_user_profile(user=user)
            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 = get_user_profile(user=user)
                    else:
                        perm_object = user

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

        return (changed_permissions, changed_users, warnings)
示例#2
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()
示例#3
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()
示例#4
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 = get_user_profile(user=user)
            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 = get_user_profile(user=user)
                    else:
                        perm_object = user

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

        return (changed_permissions, changed_users, warnings)
示例#5
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
示例#6
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
示例#7
0
def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)
    profile = get_user_profile(user=user)
    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context: extra_context = dict()
    extra_context['profile'] = profile
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#8
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())
示例#9
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()
        try:
            django.core.validators.validate_email(identification)
            try: user = User.objects.get(email__iexact=identification)
            except User.DoesNotExist: return None
        except django.core.validators.ValidationError:
            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
示例#10
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', ['You\'re already known under this email.'])},
            # An e-mail address used by another
            {'data': {'email': '*****@*****.**'},
             'error': ('email', ['This email is already in use. Please supply a different email.'])},
        ]

        # Override locale settings since we are checking for existence of error
        # messaged written in english. Note: it should not be necessasy but
        # we have experienced such locale issues during tests on Travis builds.
        # See: https://github.com/bread-and-pepper/django-userena/issues/446
        with override('en'):
            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())
示例#11
0
def profile_edit(request,
                 edit_profile_form=EditProfileFormExtra,
                 template_name='userena/profile_form.html',
                 success_url=settings.BASE_URL + 'dashboard',
                 extra_context=None, **kwargs):

    if request.user.is_authenticated():
        username = request.user.username
        user = get_object_or_404(get_user_model(),
                                 username__iexact=username)

        profile = user.get_profile()

        user_initial = {'first_name': user.first_name,
                        'last_name': user.last_name}

        form = edit_profile_form(instance=profile, initial=user_initial)

        if request.method == 'POST':
            form = edit_profile_form(request.POST, request.FILES, instance=profile,
                                     initial=user_initial)

            if form.is_valid():
                profile = form.save()
                return redirect(success_url)

        if not extra_context: extra_context = dict()
        extra_context['form'] = form
        extra_context['profile'] = profile
        extra_context['request'] = request
        return userena.views.ExtraContextTemplateView.as_view(template_name=template_name,
            extra_context=extra_context)(request)

    return userena.views.signup(request, **kwargs)
示例#12
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']
示例#13
0
    def get_context_data(self, username, extra_context=None, *args, **kwargs):
        context = super(ProfileDetailView, self).get_context_data(*args, **kwargs)
        
        user = get_object_or_404(get_user_model(),
                                 username__iexact=username)

        # Get profile
        profile_model = get_profile_model()
        try:
            profile = user.get_profile()
        except profile_model.DoesNotExist:
            profile = profile_model.objects.create(user=user)

        # Lookup badges
        services = profile.services.all()
        services_detailed = profile.service_detailed.all()
        badges = ServiceBadge.objects.filter(services__in=services).distinct().order_by('category')
        
        for b in badges:
            b.user_services = []
            for service_detailed in services_detailed:
                if service_detailed.service in b.services.all():
                    b.user_services.append(service_detailed)

        # Check perms
        if not profile.can_view_profile(self.request.user):
            return HttpResponseForbidden(_("You don't have permission to view this profile."))

        # context
        context['profile'] = profile
        context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
        context['badges'] = badges

        return context
示例#14
0
def profile_detail(
        request,
        username,
        template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
        extra_context=None,
        **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)
    profile = get_user_profile(user=user)
    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context: extra_context = dict()
    extra_context['profile'] = profile
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#15
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()
        try:
            django.core.validators.validate_email(identification)
            try: user = User.objects.get(email__iexact=identification)
            except User.DoesNotExist: return None
        except django.core.validators.ValidationError:
            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
示例#16
0
    def setUp(self):
        # Add the models to the db.

        # Call the original method that does the fixtures etc.
        super(UserenaSignupModelTests, self).setUp()

        call_command('syncdb', interactive=False, verbosity=0)

        for model, perms in ASSIGNED_PERMISSIONS.items():
            for perm in perms:
                if model == 'profile':
                    model_obj = get_profile_model()
                else:
                    model_obj = get_user_model()

                model_content_type = ContentType.objects.get_for_model(
                    model_obj)

                try:
                    Permission.objects.get(codename=perm[0],
                                           content_type=model_content_type)
                except Permission.DoesNotExist:
                    Permission.objects.create(name=perm[1],
                                              codename=perm[0],
                                              content_type=model_content_type)
示例#17
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 userena_settings.USERENA_ACTIVATION_REQUIRED and 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 your email for verification steps.'))
         raise forms.ValidationError(_('This email is already in use. Please supply a different email.'))
     return self.cleaned_data['email']
示例#18
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']
示例#19
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 userena_settings.USERENA_ACTIVATION_REQUIRED and 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 your email for verification steps.'))
         raise forms.ValidationError(_('This email is already in use. Please supply a different email.'))
     return self.cleaned_data['email']
示例#20
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
示例#21
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
示例#22
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 userena_settings.USERENA_ACTIVATION_REQUIRED and 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 your 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']
示例#23
0
文件: views.py 项目: webvul/crawler
 def get_queryset(self):
     username = self.kwargs['username']
     self.recipient = get_object_or_404(get_user_model(),
                                        username__iexact=username)
     queryset = Message.objects.get_conversation_between(self.request.user,
                                                         self.recipient)
     self._update_unread_messages(queryset)
     return queryset
示例#24
0
def profile_detail_extended(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_detail_extended.html', success_url=None,extra_context=None, **kwargs):
	user = get_object_or_404(get_user_model(), username__iexact=username)
	profile = get_user_profile(user=user)
	if not extra_context: extra_context = dict()
	extra_context['profile'] = profile
	extra_context['profExpData'] = Profile_Experience.objects.filter(profile = profile)
	extra_context['projExpData'] = Project_Experience.objects.filter(profile = profile)
	extra_context['awardsData'] = Awards.objects.filter(profile = profile)
	return ExtraContextTemplateView.as_view(template_name=template_name, extra_context=extra_context)(request)
示例#25
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 userena_settings.USERENA_ACTIVATION_REQUIRED and 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 your 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']
示例#26
0
def message_compose(request, recipients=None, compose_form=ComposeForm,
                    success_url=None, template_name="umessages/message_form.html",
                    recipient_filter=None, extra_context=None):
    """
    Compose a new message

    :recipients:
        String containing the usernames to whom the message is send to. Can be
        multiple username by seperating them with a ``+`` sign.

    :param compose_form:
        The form that is used for getting neccesary information. Defaults to
        :class:`ComposeForm`.

    :param success_url:
        String containing the named url which to redirect to after successfull
        sending a message. Defaults to ``userena_umessages_list`` if there are
        multiple recipients. If there is only one recipient, will redirect to
        ``userena_umessages_detail`` page, showing the conversation.

    :param template_name:
        String containing the name of the template that is used.

    :param recipient_filter:
        A list of :class:`User` that don"t want to receive any messages.

    :param extra_context:
        Dictionary with extra variables supplied to the template.

    **Context**

    ``form``
        The form that is used.

    """
    initial_data = dict()

    if recipients:
        username_list = [r.strip() for r in recipients.split("+")]
        recipients = [u for u in get_user_model().objects.filter(username__in=username_list)]
        initial_data["to"] = recipients

    form = compose_form(initial=initial_data)
    if request.method == "POST":
        form = compose_form(request.POST)
        if form.is_valid():
            requested_redirect = request.REQUEST.get("next", False)

            message = form.save(request.user)
            recipients = form.cleaned_data['to']

            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request, _('Message is sent.'),
                                 fail_silently=True)
            return Response({'id':message.id})
        else:
    	    return Response(form.errors)
示例#27
0
    def create_user_with_name(self, username, first_name, last_name, 
                              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, first_name, last_name, 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(first_name, last_name)

        return new_user
示例#28
0
def profile_detail(
        request,
        username,
        template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
        extra_context=None,
        **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(
            _("You don't have permission to view this profile."))
    if not extra_context:
        extra_context = dict()

    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    extra_context['location'] = request.user_location["user_location_lat_lon"]
    extra_context['is_admin'] = user.is_superuser
    extra_context['per_page'] = int(request.GET.get('per_page', 6))

    tabs_page = "profile-detail"
    active_tab = request.session.get(tabs_page, "account-events")
    extra_context['active_tab'] = active_tab

    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#29
0
def profile_detail(request, username,extra_context=None, **kwargs):

    template_name = 'userena/profile_detail.html'
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)
    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    return render(request, template_name, {'profile': profile,'bulletins' : Post.objects.filter(tag1='announcement').order_by("-time")})
示例#30
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
示例#31
0
def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)

    if Pago.objects.filter(user=user).exists():
        last_pago = Pago.objects.filter(user=user).order_by('-fecha_expiracion').get()
    else:
        last_pago = None

    today = date.today()

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)


    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(_("You don't have permission to view this profile."))
    if not extra_context: extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    if last_pago is None or last_pago.fecha_expiracion < today:
        extra_context['suscripcion_status'] = "Inactiva"
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#32
0
def profile_detail(request, username, template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE, extra_context=None, **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(_("You don't have permission to view this profile."))
    if not extra_context:
        extra_context = dict()
    
    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    extra_context['location'] = request.user_location["user_location_lat_lon"]
    extra_context['is_admin'] = user.is_superuser
    extra_context['per_page'] = int(request.GET.get('per_page', 6))

    tabs_page = "profile-detail"
    active_tab = request.session.get(tabs_page, "account-events")
    extra_context['active_tab'] = active_tab

    return ExtraContextTemplateView.as_view(
        template_name=template_name,
        extra_context=extra_context
    )(request)    
示例#33
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
示例#34
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)
示例#35
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)
示例#36
0
def _friends(request,username,
                 template_name='friends.html', success_url=None,
                 extra_context=None):
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)
    profile = user.get_profile()
    user_initial = {'first_name': user.first_name,
                    'last_name': user.last_name}
    data = locals()
    if not extra_context: extra_context = dict()
    #extra_context['ftype'] = ftype
    extra_context['profile'] = profile
    #extra_context['user'] = user
    #more_data = {'username':username,'ftype':ftype}
    #return direct_to_template(template = 'friends.html', kwargs=kwargs)
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#37
0
def profile_detail(request, username, extra_context=None, **kwargs):

    template_name = 'userena/profile_detail.html'
    user = get_object_or_404(get_user_model(), username__iexact=username)
    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    return render(
        request, template_name, {
            'profile': profile,
            'bulletins':
            Post.objects.filter(tag1='announcement').order_by("-time")
        })
示例#38
0
def profile_detail(
        request,
        username,
        template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
        extra_context=None,
        **kwargs):
    """
        Detailed view of an user.

        :param username:
            String of the username of which the profile should be viewed.

        :param template_name:
            String representing the template name that should be used to
            display the profile.

        :param extra_context:
            Dictionary of variables which should be supplied to the template.
            The ``profile`` key is always the current profile.

        **Context**

        ``profile``
            Instance of the currently viewed ``Profile``.
    """
    user = get_object_or_404(get_user_model(), username__iexact=username)
    current_tasks = Task.objects.filter(edition=Edition.get_current)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context:
        extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['tasks'] = current_tasks.filter(volunteers__user=user)
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    check_profile_completeness(request, user.get_profile())
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#39
0
def profile_edit(request,
                 username,
                 edit_profile_form=EditProfileForm,
                 template_name='userena/profile_form.html',
                 success_url=None,
                 extra_context=None,
                 **kwargs):
    user = get_object_or_404(get_user_model(), username__iexact=username)

    profile = user.get_profile()

    user_initial = {'first_name': user.first_name, 'last_name': user.last_name}

    form = edit_profile_form(instance=profile, initial=user_initial)

    if request.method == 'POST':
        form = edit_profile_form(request.POST,
                                 request.FILES,
                                 instance=profile,
                                 initial=user_initial)

        if form.is_valid():
            profile = form.save()

            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request,
                                 _('Your profile has been updated.'),
                                 fail_silently=True)

            if success_url:
                # Send a signal that the profile has changed
                userena_signals.profile_change.send(sender=None, user=user)
                redirect_to = success_url
            else:
                redirect_to = reverse('userena_profile_detail',
                                      kwargs={'username': username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = profile
    extra_context['bulletins'] = Post.objects.filter(
        tag1='announcement').order_by("-time")
    return render(request, template_name, extra_context)
示例#40
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.

        """

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

        # Give permissions to view and change profile
        for perm in ASSIGNED_PERMISSIONS["profile"]:
            assign_perm(perm[0], new_user, get_user_profile(user=new_user))

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

        userena_profile = self.create_userena_profile(new_user)

        if send_email:
            userena_profile.send_activation_email()

        return new_user
示例#41
0
def profile_listview(
        request,
        username,
        template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
        extra_context=None,
        **kwargs):
    """
    note: 'extra_context' is a dictionary of variables which should be supplied to the template.
    """

    user = get_object_or_404(get_user_model(), username__iexact=username)
    fullsalelist = Entry.objects.filter(
        author__username__iexact=username).order_by('-pub_date')
    userreviews = UserReview.objects.filter(
        name__username__iexact=username).order_by('-pub_date')

    if request.is_ajax():
        object_name = request.POST.get('entryname')
        targetobject = Entry.objects.get(headline=object_name)
        if request.user.username == targetobject.author.username:
            targetobject.delete()
        return HttpResponseRedirect('/storefront/')

    profile_model = get_profile_model()
    try:
        profile = user.my_profile
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context: extra_context = dict()

    if username == request.user.username:
        pageowner = "True"
        extra_context['pageowner'] = pageowner
    extra_context['profile'] = user.my_profile
    extra_context['fullsalelist'] = fullsalelist
    extra_context['userreviews'] = userreviews
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL

    return ExtraContextTemplateView.as_view(
        template_name='profile_listview.html',
        extra_context=extra_context)(request)
示例#42
0
def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)
    ganaderia = 'Sin asignar'
    if Ganaderia.objects.all():
        if Ganaderia.objects.filter(perfil=user.id):
            ganaderia = Ganaderia.objects.get(perfil=user.id)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context: extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    extra_context['ganaderia'] = ganaderia
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#43
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
示例#44
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
示例#45
0
文件: views.py 项目: dosberg/Feedback
def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):

    user = get_object_or_404(get_user_model(),
                             username__iexact=username)

    profile_model = get_profile_model()
    
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)
            
    if not extra_context: extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['company'] = Company.objects.get(id=profile.company_id)
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#46
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())
示例#47
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')
示例#48
0
def profile_detail(request, username):
    """
        Add extra context and returns userena_profile_detail view
    """
    extra_context = {}
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)

    # Get profile
    profile_model = get_profile_model()
    profile = user.get_profile()
    # Check perms
    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(_("You don't have permission to view this profile."))

    # context
    extra_context['profile'] = profile
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL

    return userena_profile_detail(request=request, username=username, extra_context=extra_context)
示例#49
0
def profile_detail(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):
    """
    Detailed view of an user.

    :param username:
        String of the username of which the profile should be viewed.

    :param template_name:
        String representing the template name that should be used to display
        the profile.

    :param extra_context:
        Dictionary of variables which should be supplied to the template. The
        ``profile`` key is always the current profile.

    **Context**

    ``profile``
        Instance of the currently viewed ``Profile``.

    """
    user = get_object_or_404(get_user_model(),
                             username__iexact=username)

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    request.breadcrumbs((('Home', reverse('index')), ('{}\'s profile'.format(user.username), '')))

    if not profile.can_view_profile(request.user):
        return HttpResponseForbidden(_("You don't have permission to view this profile."))
    if not extra_context: extra_context = dict()
    extra_context['profile'] = user.get_profile()
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    return ExtraContextTemplateView.as_view(template_name=template_name,
                                            extra_context=extra_context)(request)
示例#50
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')
示例#51
0
def profile_listview(request, username,
    template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
    extra_context=None, **kwargs):

    """
    note: 'extra_context' is a dictionary of variables which should be supplied to the template.
    """

    user = get_object_or_404(get_user_model(),
                             username__iexact=username)
    fullsalelist = Entry.objects.filter(author__username__iexact=username).order_by('-pub_date')
    userreviews = UserReview.objects.filter(name__username__iexact=username).order_by('-pub_date')

    if request.is_ajax():
      	object_name = request.POST.get('entryname')
      	targetobject = Entry.objects.get(headline=object_name)
      	if request.user.username == targetobject.author.username:
         	targetobject.delete()
      	return HttpResponseRedirect('/storefront/')

    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except profile_model.DoesNotExist:
        profile = profile_model.objects.create(user=user)

    if not profile.can_view_profile(request.user):
        raise PermissionDenied
    if not extra_context: extra_context = dict()
    
    if username == request.user.username:
        pageowner="True"
        extra_context['pageowner'] = pageowner
    extra_context['profile'] = user.get_profile()
    extra_context['fullsalelist'] = fullsalelist
    extra_context['userreviews'] = userreviews
    extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
    
    return ExtraContextTemplateView.as_view(template_name='profile_listview.html',
                                            extra_context=extra_context)(request)
示例#52
0
def direct_to_user_template(request,
                            username,
                            template_name,
                            extra_context=None):
    """
    Simple wrapper for Django's :func:`direct_to_template` view.

    This view is used when you want to show a template to a specific user. A
    wrapper for :func:`direct_to_template` where the template also has access to
    the user that is found with ``username``. For ex. used after signup,
    activation and confirmation of a new e-mail.

    :param username:
        String defining the username of the user that made the action.

    :param template_name:
        String defining the name of the template to use. Defaults to
        ``userena/signup_complete.html``.

    **Keyword arguments**

    ``extra_context``
        A dictionary containing extra variables that should be passed to the
        rendered template. The ``account`` key is always the ``User``
        that completed the action.

    **Extra context**

    ``viewed_user``
        The currently :class:`User` that is viewed.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)

    if not extra_context: extra_context = dict()
    extra_context['viewed_user'] = user
    extra_context['profile'] = user.get_profile()
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#53
0
    def get_context_data(self, username, extra_context=None, *args, **kwargs):
        context = super(ProfileDetailView, self).get_context_data(*args, **kwargs)
        
        user = get_object_or_404(get_user_model(),
                                 username__iexact=username)

        # Get profile
        profile_model = get_profile_model()
        try:
            profile = user.get_profile()
        except profile_model.DoesNotExist:
            profile = profile_model.objects.create(user=user)

        # Check perms
        if not profile.can_view_profile(self.request.user):
            return HttpResponseForbidden(_("You don't have permission to view this profile."))

        # context
        context['profile'] = profile
        context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL

        return context
示例#54
0
def disabled_account(request, username, template_name, extra_context=None):
    """
    Checks if the account is disabled, if so, returns the disabled account template.

    :param username:
        String defining the username of the user that made the action.

    :param template_name:
        String defining the name of the template to use. Defaults to
        ``userena/signup_complete.html``.

    **Keyword arguments**

    ``extra_context``
        A dictionary containing extra variables that should be passed to the
        rendered template. The ``account`` key is always the ``User``
        that completed the action.

    **Extra context**

    ``viewed_user``
        The currently :class:`User` that is viewed.

    ``profile``
        Profile of the viewed user.
    
    """
    user = get_object_or_404(get_user_model(), username__iexact=username)

    if user.is_active:
        raise Http404

    if not extra_context: extra_context = dict()
    extra_context['viewed_user'] = user
    extra_context['profile'] = user.get_profile()
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#55
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', ['You\'re already known under this email.'])
            },
            # An e-mail address used by another
            {
                'data': {
                    'email': '*****@*****.**'
                },
                'error': ('email', [
                    'This email is already in use. Please supply a different email.'
                ])
            },
        ]

        # Override locale settings since we are checking for existence of error
        # messaged written in english. Note: it should not be necessasy but
        # we have experienced such locale issues during tests on Travis builds.
        # See: https://github.com/bread-and-pepper/django-userena/issues/446
        with override('en'):
            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())
示例#56
0
from django.http import HttpRequest
from django.test import TestCase

from userena.tests.profiles.models import Profile
from userena.middleware import UserenaLocaleMiddleware
from userena import settings as userena_settings
from userena.utils import get_user_model, get_user_profile, get_profile_model

User = get_user_model()


def has_profile(user):
    """Test utility function to check if user has profile"""
    profile_model = get_profile_model()
    try:
        profile = user.get_profile()
    except AttributeError:
        related_name = profile_model._meta.get_field_by_name('user')[0]\
                                    .related_query_name()
        profile = getattr(user, related_name, None)
    except profile_model.DoesNotExist:
        profile = None

    return bool(profile)


class UserenaLocaleMiddlewareTests(TestCase):
    """ Test the ``UserenaLocaleMiddleware`` """
    fixtures = ['users', 'profiles']

    def _get_request_with_user(self, user):
示例#57
0
def password_change(request,
                    username,
                    template_name='userena/password_form.html',
                    pass_form=PasswordChangeForm,
                    success_url=None,
                    extra_context=None):
    """ Change password of user.

    This view is almost a mirror of the view supplied in
    :func:`contrib.auth.views.password_change`, with the minor change that in
    this view we also use the username to change the password. This was needed
    to keep our URLs logical (and REST) across the entire application. And
    that in a later stadium administrators can also change the users password
    through the web application itself.

    :param username:
        String supplying the username of the user who's password is about to be
        changed.

    :param template_name:
        String of the name of the template that is used to display the password
        change form. Defaults to ``userena/password_form.html``.

    :param pass_form:
        Form used to change password. Default is the form supplied by Django
        itself named ``PasswordChangeForm``.

    :param success_url:
        Named URL that is passed onto a :func:`reverse` function with
        ``username`` of the active user. Defaults to the
        ``userena_password_complete`` URL.

    :param extra_context:
        Dictionary of extra variables that are passed on to the template. The
        ``form`` key is always used by the form supplied by ``pass_form``.

    **Context**

    ``form``
        Form used to change the password.

    """
    user = get_object_or_404(get_user_model(), username__iexact=username)

    form = pass_form(user=user)

    if request.method == "POST":
        form = pass_form(user=user, data=request.POST)
        if form.is_valid():
            form.save()

            # Send a signal that the password has changed
            userena_signals.password_complete.send(sender=None, user=user)

            if success_url: redirect_to = success_url
            else:
                redirect_to = reverse(
                    'accounts:userena_password_change_complete',
                    kwargs={'username': user.username})
            return redirect(redirect_to)

    if not extra_context: extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = user.get_profile()
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)
示例#58
0
文件: admin.py 项目: zztemp001/yaayaa
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 userena.models import UserenaSignup
from 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())
示例#59
0
def profile_edit(request,
                 username,
                 edit_profile_form=EditProfileForm,
                 template_name='userena/profile_form.html',
                 success_url=None,
                 extra_context=None,
                 **kwargs):
    """
        Edit profile.

        Edits a profile selected by the supplied username. First checks
        permissions if the user is allowed to edit this profile, if denied will
        show a 404. When the profile is successfully edited will redirect to
        ``success_url``.

        :param username:
            Username of the user which profile should be edited.

        :param edit_profile_form:

            Form that is used to edit the profile. The
            :func:`EditProfileForm.save` method of this form will be called
            when the form :func:`EditProfileForm.is_valid`.  Defaults to
            :class:`EditProfileForm` from userena.

        :param template_name:
            String of the template that is used to render this view. Defaults
            to ``userena/edit_profile_form.html``.

        :param success_url:
            Named URL which will be passed on to a django ``reverse`` function
            after the form is successfully saved. Defaults to the
            ``userena_detail`` url.

        :param extra_context:
            Dictionary containing variables that are passed on to the
            ``template_name`` template.  ``form`` key will always be the form
            used to edit the profile, and the ``profile`` key is always the
            edited profile.

        **Context**

        ``form``
            Form that is used to alter the profile.

        ``profile``
            Instance of the ``Profile`` that is edited.
    """
    user = get_object_or_404(get_user_model(), username__iexact=username)

    profile = user.get_profile()

    user_initial = {'first_name': user.first_name, 'last_name': user.last_name}

    form = edit_profile_form(instance=profile, initial=user_initial)

    if request.method == 'POST':
        form = edit_profile_form(request.POST,
                                 request.FILES,
                                 instance=profile,
                                 initial=user_initial)

        if form.is_valid():
            profile = form.save(commit=False)
            profile.save()

            if userena_settings.USERENA_USE_MESSAGES:
                messages.success(request,
                                 _('Your profile has been updated.'),
                                 fail_silently=True)

            if success_url:
                # Send a signal that the profile has changed
                userena_signals.profile_change.send(sender=None, user=user)
                redirect_to = success_url
            else:
                redirect_to = reverse('userena_profile_detail',
                                      kwargs={'username': username})
            return redirect(redirect_to)

    if not extra_context:
        extra_context = dict()
    extra_context['form'] = form
    extra_context['profile'] = profile
    return ExtraContextTemplateView.as_view(
        template_name=template_name, extra_context=extra_context)(request)