Beispiel #1
0
    def add_admin_membership_action(self, request, agora, username, welcome_message, **kwargs):
        '''
        Adds an admin (specified with username) to this agora, sending a
        welcome message to this new admin via email
        '''
        if not re.match("^[a-zA-Z0-9_]+$", username):
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
        user = get_object_or_404(User, username=username)

        # remve the request admin membership status and add user to the agora
        remove_perm('requested_admin_membership', user, agora)
        agora.admins.add(user)
        agora.save()

        # create an action for the event
        action.send(request.user, verb='added admin',
            action_object=agora, ipaddr=request.META.get('REMOTE_ADDR'),
            target=user,
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if user.get_profile().has_perms('receive_email_updates'):
            translation.activate(user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=user,
                notification_text=_('As administrator of %(agora)s, %(user)s has '
                    'himself promoted you to admin of this agora. You can remove '
                    'your admin membership at anytime, and if you think he is '
                    'spamming you please contact with this website '
                    'administrators.\n\n') % dict(
                        agora=agora.get_full_name(),
                        user=request.user.username
                    ) + welcome_message,
                to=user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - Promoted to admin of agora %(agora)s') % dict(
                    site=Site.objects.get_current().domain,
                    agora=agora.get_full_name()
                ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #2
0
    def remove_membership_action(self, request, agora, username, goodbye_message, **kwargs):
        '''
        Remove a member (specified with username) from this agora, sending a
        goodbye message to this member via email
        '''
        if not re.match("^[a-zA-Z0-9_]+$", username):
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
        user = get_object_or_404(User, username=username)

        # user might not be allowed to leave (because he's the owner, or because
        # he's not a member of this agora at all)
        if not agora.has_perms('leave', user):
            raise ImmediateHttpResponse(response=http.HttpForbidden())

        agora.members.remove(user)
        agora.save()

        # create an action for the event
        action.send(request.user, verb='removed member',
            action_object=agora, ipaddr=request.META.get('REMOTE_ADDR'),
            target=user,
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if user.get_profile().has_perms('receive_email_updates'):
            translation.activate(user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=user,
                notification_text=_('Your have been removed from membership '
                    'from %(agora)s . Sorry about that!\n\n') % dict(
                            agora=agora.get_full_name()
                        ) + goodbye_message,
                to=user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - membership removed from '
                    '%(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #3
0
    def add_to_agora(self, request=None, agora_name=None, agora_id=None):
        '''
        Add the user to the specified agora. The agora is specified by its full
        name or id, for example agora_name="username/agoraname" or agora_id=3.
        '''

        if agora_name:
            username, agoraname = agora_name.split("/")
            agora = get_object_or_404(Agora,
                                      name=agoraname,
                                      creator__username=username)
            agora.members.add(self.user)
            agora.save()
        else:
            agora = get_object_or_404(Agora, pk=agora_id)
            agora.members.add(self.user)
            agora.save()

        send_action(self.user,
                    verb='joined',
                    action_object=agora,
                    request=request)

        if not is_following(self.user, agora):
            follow(self.user, agora, actor_only=False, request=request)

        # Mail to the user
        if not self.has_perms('receive_email_updates'):
            return

        translation.activate(self.user.get_profile().lang_code)
        context = get_base_email_context(request)
        context.update(
            dict(agora=agora,
                 other_user=self.user,
                 notification_text=_('You just joined %(agora)s. '
                                     'Congratulations!') %
                 dict(agora=agora.get_full_name()),
                 to=self.user))

        email = EmailMultiAlternatives(
            subject=_('%(site)s - you are now member of %(agora)s') %
            dict(site=Site.objects.get_current().domain,
                 agora=agora.get_full_name()),
            body=render_to_string('agora_core/emails/agora_notification.txt',
                                  context),
            to=[self.user.email])

        email.attach_alternative(
            render_to_string('agora_core/emails/agora_notification.html',
                             context), "text/html")
        email.send()
        translation.deactivate()
Beispiel #4
0
    def cancel_vote_action(self, request, election, **kwargs):
        '''
        Cancels a vote
        '''

        election_url = election.get_link()
        vote = election.get_vote_for_voter(request.user)

        if not vote or not vote.is_direct:
            data = dict(errors=_('You didn\'t participate in this election.'))
            return self.raise_error(request, http.HttpBadRequest, data)

        vote.invalidated_at_date = timezone.now()
        vote.is_counted = False
        vote.save()

        context = get_base_email_context(request)
        context.update(
            dict(election=election,
                 election_url=election_url,
                 to=vote.voter,
                 agora_url=election.agora.get_link()))

        try:
            context['delegate'] = get_delegate_in_agora(
                vote.voter, election.agora)
        except:
            pass

        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            email = EmailMultiAlternatives(
                subject=_('Vote cancelled for election %s') %
                election.pretty_name,
                body=render_to_string('agora_core/emails/vote_cancelled.txt',
                                      context),
                to=[vote.voter.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/vote_cancelled.html',
                                 context), "text/html")
            email.send()
            translation.deactivate()

        action.send(request.user,
                    verb='vote cancelled',
                    action_object=election,
                    target=election.agora,
                    ipaddr=request.META.get('REMOTE_ADDR'),
                    geolocation=json.dumps(
                        geolocate_ip(request.META.get('REMOTE_ADDR'))))

        return self.create_response(request, dict(status="success"))
Beispiel #5
0
    def deny_admin_membership_action(self, request, agora, username, **kwargs):
        '''
        Deny an admin membership request from the given username user in an agora
        '''
        if not re.match("^[a-zA-Z0-9_]+$", username):
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
        user = get_object_or_404(User, username=username)

        # One can only accept admin membership if it can cancel it, which means
        # if it's requested
        if not agora.has_perms('cancel_admin_membership_request', user):
            raise ImmediateHttpResponse(response=http.HttpForbidden())

        # remove the request admin membership status and add user to the agora
        remove_perm('requested_admin_membership', user, agora)

        # create an action for the event
        action.send(request.user, verb='denied admin membership request',
            action_object=agora, ipaddr=request.META.get('REMOTE_ADDR'),
            target=user,
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if user.get_profile().has_perms('receive_email_updates'):
            translation.activate(user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=user,
                notification_text=_('Your admin membership request at %(agora)s '
                    'has been denied. Sorry about that!') % dict(
                        agora=agora.get_full_name()
                    ),
                to=user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - admin membership request denied at '
                    '%(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #6
0
    def cancel_vote_delegation(self, request, agora, **kwargs):
        '''
        Cancel a delegated vote
        '''

        # get the delegated vote, if any
        vote = agora.get_delegated_vote_for_user(request.user)
        if not vote:
            data = dict(errors=_('Your vote is not currently delegated.'))
            return self.raise_error(request, http.HttpBadRequest, data)

        # invalidate the vote
        vote.invalidated_at_date = timezone.now()
        vote.is_counted = False
        vote.save()

        # create an action for the event
        action.send(request.user, verb='cancelled vote delegation',
            action_object=agora, ipaddr=request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=request.user,
                notification_text=_('Your hav removed your vote delegation '
                    'from %(agora)s') % dict(
                            agora=agora.get_full_name()
                        ),
                to=request.user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - admin permissions removed from '
                    '%(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[request.user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
    def add_to_agora(self, request=None, agora_name=None, agora_id=None):
        '''
        Add the user to the specified agora. The agora is specified by its full
        name or id, for example agora_name="username/agoraname" or agora_id=3.
        '''

        if agora_name:
            username, agoraname = agora_name.split("/")
            agora = get_object_or_404(Agora, name=agoraname,
                creator__username=username)
            agora.members.add(self.user)
            agora.save()
        else:
            agora = get_object_or_404(Agora, pk=agora_id)
            agora.members.add(self.user)
            agora.save()

        send_action(self.user, verb='joined', action_object=agora, request=request)

        if not is_following(self.user, agora):
            follow(self.user, agora, actor_only=False, request=request)

        # Mail to the user
        if not self.has_perms('receive_email_updates'):
            return

        translation.activate(self.user.get_profile().lang_code)
        context = get_base_email_context(request)
        context.update(dict(
            agora=agora,
            other_user=self.user,
            notification_text=_('You just joined %(agora)s. '
                'Congratulations!') % dict(agora=agora.get_full_name()),
            to=self.user
        ))

        email = EmailMultiAlternatives(
            subject=_('%(site)s - you are now member of %(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
            body=render_to_string('agora_core/emails/agora_notification.txt',
                context),
            to=[self.user.email])

        email.attach_alternative(
            render_to_string('agora_core/emails/agora_notification.html',
                context), "text/html")
        email.send()
        translation.deactivate()
Beispiel #8
0
    def cancel_vote_action(self, request, election, **kwargs):
        '''
        Cancels a vote
        '''

        election_url=election.get_link()
        vote = election.get_vote_for_voter(request.user)

        if not vote or not vote.is_direct:
            data = dict(errors=_('You didn\'t participate in this election.'))
            return self.raise_error(request, http.HttpBadRequest, data)

        vote.invalidated_at_date = datetime.datetime.now()
        vote.is_counted = False
        vote.save()

        context = get_base_email_context(request)
        context.update(dict(
            election=election,
            election_url=election_url,
            to=vote.voter,
            agora_url=election.agora.get_link()
        ))

        try:
            context['delegate'] = get_delegate_in_agora(vote.voter, election.agora)
        except:
            pass

        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            email = EmailMultiAlternatives(
                subject=_('Vote cancelled for election %s') % election.pretty_name,
                body=render_to_string('agora_core/emails/vote_cancelled.txt',
                    context),
                to=[vote.voter.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/vote_cancelled.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        action.send(request.user, verb='vote cancelled', action_object=election,
            target=election.agora, ipaddr=request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        return self.create_response(request, dict(status="success"))
Beispiel #9
0
    def approve_action(self, request, election, **kwargs):
        '''
        Requests membership from authenticated user to an agora
        '''
        election.is_approved = True
        election.save()

        action.send(request.user,
                    verb='approved',
                    action_object=election,
                    target=election.agora,
                    ipaddr=request.META.get('REMOTE_ADDR'),
                    geolocation=json.dumps(
                        geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(
                dict(agora=election.agora,
                     other_user=request.user,
                     notification_text=_(
                         'Election %(election)s approved at agora '
                         '%(agora)s. Congratulations!') %
                     dict(agora=election.agora.get_full_name(),
                          election=election.pretty_name),
                     to=request.user,
                     extra_urls=[
                         dict(url_title=_("Election URL"),
                              url=election.get_link())
                     ]))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - Election %(election)s approved') %
                dict(site=Site.objects.get_current().domain,
                     election=election.pretty_name),
                body=render_to_string(
                    'agora_core/emails/agora_notification.txt', context),
                to=[request.user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                                 context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #10
0
    def approve_action(self, request, election, **kwargs):
        '''
        Requests membership from authenticated user to an agora
        '''
        election.is_approved = True
        election.approved_at_date = election.last_modified_at_date = timezone.now()
        election.save()

        action.send(request.user, verb='approved', action_object=election,
            target=election.agora, ipaddr=request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=election.agora,
                other_user=request.user,
                notification_text=_('Election %(election)s approved at agora '
                    '%(agora)s. Congratulations!') % dict(
                        agora=election.agora.get_full_name(),
                        election=election.pretty_name
                    ),
                to=request.user,
                extra_urls=[dict(
                    url_title=_("Election URL"),
                    url=election.get_link()
                )]
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - Election %(election)s approved') % dict(
                            site=Site.objects.get_current().domain,
                            election=election.pretty_name
                        ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[request.user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #11
0
    def leave_action(self, request, agora, **kwargs):
        '''
        Remove a member (specified with username) from this agora, sending a
        goodbye message to this member via email
        '''
        agora.members.remove(request.user)
        agora.save()

        # create an action for the event
        action.send(request.user, verb='left',
            action_object=agora, ipaddr=request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        # Mail to the user
        if request.user.get_profile().has_perms('receive_email_updates'):
            translation.activate(request.user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=request.user,
                notification_text=_('You have removed your membership '
                    'from %(agora)s') % dict(
                            agora=agora.get_full_name()
                        ),
                to=request.user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - membership removed from '
                    '%(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[request.user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #12
0
    def save(self):
        translation.activate(self.target_user.get_profile().lang_code)
        context = get_base_email_context(self.request)
        context['to'] = self.target_user
        context['from'] = self.request.user
        context['comment'] = self.cleaned_data['comment']
        datatuples = [
            (_('Message from %s') %
             self.request.user.get_profile().get_fullname(),
             render_to_string('agora_core/emails/user_mail.txt', context),
             render_to_string('agora_core/emails/user_mail.html',
                              context), None, [self.target_user.email])
        ]

        translation.deactivate()

        send_mass_html_mail(datatuples)

        return None
Beispiel #13
0
    def join_action(self, request, agora, **kwargs):
        '''
        Action that an user can execute to join an agora if it has permissions
        '''
        agora.members.add(request.user)
        agora.save()

        action.send(request.user, verb='joined', action_object=agora,
            ipaddr=request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR'))))

        if not is_following(request.user, agora):
            follow(request.user, agora, actor_only=False, request=request)

        # Mail to the user
        user = request.user
        if user.get_profile().has_perms('receive_email_updates'):
            translation.activate(user.get_profile().lang_code)
            context = get_base_email_context(request)
            context.update(dict(
                agora=agora,
                other_user=user,
                notification_text=_('You just joined %(agora)s. '
                    'Congratulations!') % dict(agora=agora.get_full_name()),
                to=user
            ))

            email = EmailMultiAlternatives(
                subject=_('%(site)s - you are now member of %(agora)s') % dict(
                            site=Site.objects.get_current().domain,
                            agora=agora.get_full_name()
                        ),
                body=render_to_string('agora_core/emails/agora_notification.txt',
                    context),
                to=[user.email])

            email.attach_alternative(
                render_to_string('agora_core/emails/agora_notification.html',
                    context), "text/html")
            email.send()
            translation.deactivate()

        return self.create_response(request, dict(status="success"))
Beispiel #14
0
    def save(self):
        translation.activate(self.target_user.get_profile().lang_code)
        context = get_base_email_context(self.request)
        context["to"] = self.target_user
        context["from"] = self.request.user
        context["comment"] = clean_html(self.cleaned_data["comment"])
        datatuples = [
            (
                _("Message from %s") % self.request.user.get_profile().get_fullname(),
                render_to_string("agora_core/emails/user_mail.txt", context),
                render_to_string("agora_core/emails/user_mail.html", context),
                None,
                [self.target_user.email],
            )
        ]

        translation.deactivate()

        send_mass_html_mail(datatuples)

        return None
Beispiel #15
0
    def save(self):
        translation.activate(self.target_user.get_profile().lang_code)
        context = get_base_email_context(self.request)
        context['to'] = self.target_user
        context['from'] = self.request.user
        context['comment'] = clean_html(self.cleaned_data['comment'])
        datatuples= [(
            _('Message from %s') % self.request.user.get_profile().get_fullname(),
            render_to_string('agora_core/emails/user_mail.txt',
                context),
            render_to_string('agora_core/emails/user_mail.html',
                context),
            None,
            [self.target_user.email])
        ]

        translation.deactivate()

        send_mass_html_mail(datatuples)

        return None
Beispiel #16
0
    def save(self):
        """ Creates a new user and account. Returns the newly created user. """
        username, password, first_name = (self.cleaned_data['username'],
                                          self.cleaned_data['password1'],
                                          self.cleaned_data['first_name'])

        user = self.userena_signup_obj.user
        self.userena_signup_obj.activation_key = userena_settings.USERENA_ACTIVATED
        user.is_active = True
        user.username = username
        user.set_password(password)
        user.first_name = first_name
        profile = user.get_profile()

        agora_id = profile.extra['join_agora_id']
        profile.extra = {}
        user.save()
        profile.save()
        self.userena_signup_obj.save()

        from agora_site.agora_core.models.agora import Agora
        agora = get_object_or_404(Agora, pk=agora_id)
        agora.members.add(user)
        agora.save()

        action.send(user,
                    verb='joined',
                    action_object=agora,
                    ipaddr=self.request.META.get('REMOTE_ADDR'),
                    geolocation=json.dumps(
                        geolocate_ip(self.request.META.get('REMOTE_ADDR'))))

        follow(user, agora, actor_only=False, request=self.request)

        # Mail to the user
        translation.activate(user.get_profile().lang_code)
        context = get_base_email_context(self.request)
        context.update(
            dict(agora=agora,
                 other_user=user,
                 notification_text=_('You just joined %(agora)s. '
                                     'Congratulations!') %
                 dict(agora=agora.get_full_name()),
                 to=user))

        email = EmailMultiAlternatives(
            subject=_('%(site)s - you are now member of %(agora)s') %
            dict(site=Site.objects.get_current().domain,
                 agora=agora.get_full_name()),
            body=render_to_string('agora_core/emails/agora_notification.txt',
                                  context),
            to=[user.email])

        email.attach_alternative(
            render_to_string('agora_core/emails/agora_notification.html',
                             context), "text/html")
        email.send()
        translation.deactivate()

        # Sign the user in.
        auth_user = authenticate(identification=user.email,
                                 check_password=False)
        login(self.request, auth_user)

        if userena_settings.USERENA_USE_MESSAGES:
            messages.success(
                self.request,
                _('Your account has been activated and you have been signed in.'
                  ),
                fail_silently=True)
        return user
Beispiel #17
0
    def save(self):
        """ Creates a new user and account. Returns the newly created user. """
        username, password, first_name = (self.cleaned_data['username'],
                                     self.cleaned_data['password1'],
                                     self.cleaned_data['first_name'])

        user = self.userena_signup_obj.user
        self.userena_signup_obj.activation_key = userena_settings.USERENA_ACTIVATED
        user.is_active = True
        user.username = username
        user.set_password(password)
        user.first_name = first_name
        profile = user.get_profile()

        agora_id = profile.extra['join_agora_id']
        profile.extra = {}
        user.save()
        profile.save()
        self.userena_signup_obj.save()

        from agora_site.agora_core.models.agora import Agora
        agora = get_object_or_404(Agora, pk=agora_id)
        agora.members.add(user)
        agora.save()

        action.send(user, verb='joined', action_object=agora,
            ipaddr=self.request.META.get('REMOTE_ADDR'),
            geolocation=json.dumps(geolocate_ip(self.request.META.get('REMOTE_ADDR'))))

        follow(user, agora, actor_only=False, request=self.request)

        # Mail to the user
        translation.activate(user.get_profile().lang_code)
        context = get_base_email_context(self.request)
        context.update(dict(
            agora=agora,
            other_user=user,
            notification_text=_('You just joined %(agora)s. '
                'Congratulations!') % dict(agora=agora.get_full_name()),
            to=user
        ))

        email = EmailMultiAlternatives(
            subject=_('%(site)s - you are now member of %(agora)s') % dict(
                        site=Site.objects.get_current().domain,
                        agora=agora.get_full_name()
                    ),
            body=render_to_string('agora_core/emails/agora_notification.txt',
                context),
            to=[user.email])

        email.attach_alternative(
            render_to_string('agora_core/emails/agora_notification.html',
                context), "text/html")
        email.send()
        translation.deactivate()

        # Sign the user in.
        auth_user = authenticate(identification=user.email,
                                check_password=False)
        login(self.request, auth_user)

        if userena_settings.USERENA_USE_MESSAGES:
            messages.success(self.request, _('Your account has been activated and you have been signed in.'), fail_silently=True)
        return user
Beispiel #18
0
    def user_invite(self, request, **kwargs):
        if request.method != "POST":
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())
        try:
            data = self.deserialize_post_data(request)
            emails = map(str.strip, data["emails"])
            agoraid = data["agoraid"]
        except:
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
        agora = get_object_or_404(Agora, pk=agoraid)
        welcome_message = data.get("welcome_message", _("Welcome to this agora"))

        if not agora.has_perms("admin", request.user):
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())

        for email in emails:
            q = User.objects.filter(Q(email=email) | Q(username=email))
            exists = q.exists()
            if not exists and not validate_email(email):
                # invalid email address, cannot send an email there!
                raise ImmediateHttpResponse(response=http.HttpBadRequest())

        for email in emails:
            q = User.objects.filter(Q(email=email) | Q(username=email))
            exists = q.exists()
            if exists:
                # if user exists in agora, we'll add it directly
                user = q[0]
                if user in agora.members.all():
                    continue
                # if user exists in agora, we'll add it directly
                status, resp = rest(
                    "/agora/%s/action/" % agoraid,
                    data={"action": "add_membership", "username": user.username, "welcome_message": welcome_message},
                    method="POST",
                    request=request,
                )
                if status != 200:
                    raise ImmediateHttpResponse(response=http.HttpBadRequest())
            else:
                # send invitation
                # maximum 30 characters in username
                username = str(uuid4())[:30]
                password = str(uuid4())
                user = UserenaSignup.objects.create_user(username, email, password, False, False)
                profile = user.get_profile()
                profile.lang_code = request.user.get_profile().lang_code
                profile.extra = {"join_agora_id": agoraid}
                profile.save()

                # Mail to the user
                translation.activate(user.get_profile().lang_code)
                context = get_base_email_context(request)
                context.update(
                    dict(
                        agora=agora,
                        other_user=request.user,
                        to=user,
                        invitation_link=reverse(
                            "register-complete-invite", kwargs=dict(activation_key=user.userena_signup.activation_key)
                        ),
                        welcome_message=welcome_message,
                    )
                )

                email = EmailMultiAlternatives(
                    subject=_("%(site)s - invitation to join %(agora)s")
                    % dict(site=Site.objects.get_current().domain, agora=agora.get_full_name()),
                    body=render_to_string("agora_core/emails/join_invitation.txt", context),
                    to=[user.email],
                )

                email.attach_alternative(
                    render_to_string("agora_core/emails/join_invitation.html", context), "text/html"
                )
                email.send()
                translation.deactivate()

                # add user to the default agoras if any
                for agora_name in settings.AGORA_REGISTER_AUTO_JOIN:
                    profile.add_to_agora(agora_name=agora_name, request=request)

        return self.create_response(request, {})
Beispiel #19
0
    def user_invite(self, request, **kwargs):
        if request.method != 'POST':
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())
        try:
            data = self.deserialize_post_data(request)
            emails = map(str.strip, data['emails'])
            agoraid = data['agoraid']
        except:
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
        agora = get_object_or_404(Agora, pk=agoraid)
        welcome_message = data.get('welcome_message',
                                   _("Welcome to this agora"))

        if not agora.has_perms('admin', request.user):
            raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())

        for email in emails:
            q = User.objects.filter(Q(email=email) | Q(username=email))
            exists = q.exists()
            if not exists and not validate_email(email):
                # invalid email address, cannot send an email there!
                raise ImmediateHttpResponse(response=http.HttpBadRequest())

        for email in emails:
            q = User.objects.filter(Q(email=email) | Q(username=email))
            exists = q.exists()
            if exists:
                # if user exists in agora, we'll add it directly
                user = q[0]
                if user in agora.members.all():
                    continue
                # if user exists in agora, we'll add it directly
                status, resp = rest('/agora/%s/action/' % agoraid,
                                    data={
                                        'action': 'add_membership',
                                        'username': user.username,
                                        'welcome_message': welcome_message
                                    },
                                    method="POST",
                                    request=request)
                if status != 200:
                    raise ImmediateHttpResponse(response=http.HttpBadRequest())
            else:
                # send invitation
                # maximum 30 characters in username
                username = str(uuid4())[:30]
                password = str(uuid4())
                user = UserenaSignup.objects.create_user(
                    username, email, password, False, False)
                profile = user.get_profile()
                profile.lang_code = request.user.get_profile().lang_code
                profile.extra = {'join_agora_id': agoraid}
                profile.save()

                # Mail to the user
                translation.activate(user.get_profile().lang_code)
                context = get_base_email_context(request)
                context.update(
                    dict(agora=agora,
                         other_user=request.user,
                         to=user,
                         invitation_link=reverse(
                             'register-complete-invite',
                             kwargs=dict(activation_key=user.userena_signup.
                                         activation_key)),
                         welcome_message=welcome_message))

                email = EmailMultiAlternatives(
                    subject=_('%(site)s - invitation to join %(agora)s') %
                    dict(site=Site.objects.get_current().domain,
                         agora=agora.get_full_name()),
                    body=render_to_string(
                        'agora_core/emails/join_invitation.txt', context),
                    to=[user.email])

                email.attach_alternative(
                    render_to_string('agora_core/emails/join_invitation.html',
                                     context), "text/html")
                email.send()
                translation.deactivate()

                # add user to the default agoras if any
                for agora_name in settings.AGORA_REGISTER_AUTO_JOIN:
                    profile.add_to_agora(agora_name=agora_name,
                                         request=request)

        return self.create_response(request, {})