示例#1
0
 def test_saving_and_retreiving_messages(self):
     invitation = Invitation()
     invitation.save()
 
     first_message = Message()
     first_message.text = 'The first (ever) message'
     first_message.invitation = invitation
     first_message.save()
     
     second_message = Message()
     second_message.text = 'Message the second'
     second_message.invitation = invitation
     second_message.save()
     
     saved_invitation = Invitation.objects.first()
     self.assertEqual(saved_invitation, invitation)
     
     saved_messages = Message.objects.all()
     self.assertEqual(saved_messages.count(), 2)
     
     first_saved_message = saved_messages[0]
     second_saved_message = saved_messages[1]
     
     self.assertEqual(first_saved_message.text, 'The first (ever) message')
     self.assertEqual(first_saved_message.invitation, invitation)
     self.assertEqual(second_saved_message.text, 'Message the second')   
     self.assertEqual(second_saved_message.invitation, invitation)
    def test_dispatch_and_register(self):
        """
        Long-form test that tests creating and sending an invite, and then
        registering a user by following the referral link in the invitation email.
        """
        countries = [
            Country(gwno=i, name=str(i), shape={}, simpleshape={})
            for i in range(5)
        ]
        for c in countries:
            c.save()

        i = Invitation(email="*****@*****.**")
        i.save()
        i.countries.set(countries)
        dispatchInvitation(i)

        m = mail.outbox[0]

        # Mailed flag
        self.assertTrue(i.mailed)

        # Email has proper title
        self.assertEqual(m.subject, settings.DEFAULT_EMAIL_TITLE)

        # Email contains ref. key
        self.assertIsNotNone(re.search(i.refkey, m.body))

        r = self.client.get(i.invitationLink(), follow=True)
        location, *_ = r.redirect_chain[-1]

        soup = BeautifulSoup(r.content, features="html.parser")

        regform = soup.find("form")
        usernameInput = regform.find("input", attrs={"name": "username"})

        # Email is in the username form
        self.assertEqual(usernameInput["value"], i.email)

        url = regform.action if regform.action else location
        method = regform.method if regform.method else "POST"

        getattr(self.client,
                method.lower())(url, {
                    "username": usernameInput["value"],
                    "password1": hashlib.md5(b"1234").hexdigest(),
                    "password2": hashlib.md5(b"1234").hexdigest()
                })

        # User was created
        try:
            u = User.objects.get(email=i.email)
        except User.DoesNotExist:
            self.fail("User was not created")

        # Make sure all countries were added
        self.assertEqual({c.pk
                          for c in countries},
                         {c.pk
                          for c in u.profile.countries.all()})
    def test_sent_invite_again_if_accepted_invite_exists_but_no_user_account_exists(
        self, ):
        """
        Login and send a duplicate invite where another invite already exists
        BUT there is NO user account corresponding to the invited email address
        """
        other_credentials = get_other_credentials(is_admin=False)
        Invitation.create(
            other_credentials["email"],
            inviter=self.user,
            sent=timezone.now(),
            accepted=True,
        )

        self.client.login(username="******", password="******")
        self.login_2fa()
        response = self.client.post(reverse("invite"),
                                    {"email": other_credentials["email"]},
                                    follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertContains(
            response,
            "<h1>Invitation sent to {}</h1>".format(
                other_credentials["email"]),
        )
示例#4
0
def bulkCreateInvites(data: List[InvitationRow], cohort = None)->List[Invitation]:
    res = {"messages":[],"data":{"updated":0,"added":0}}
    for entry in data:
        try:
            User.objects.get(username = entry.email)
        except User.DoesNotExist:
            pass
        else:
            res["messages"].append(f"User {entry.email} already exists")
            continue

        try:
            invitation = Invitation.objects.get(email=entry.email)
        except Invitation.DoesNotExist:
            invitation = Invitation(
                    email = entry.email
                )
            invitation.save()
            res["data"]["added"]+=1
        else:
            res["data"]["updated"]+=1

        invitation.metadata = {"position":entry.position,"affiliation":entry.affiliation}
            
        countries = []
        for cname in entry.countries:
            try:
                c = Country.objects.get(name=cname)
            except Country.DoesNotExist:
                res["messages"].append(f"Did not find country {cname} while creating invite for {entry.email}")
            else:
                countries.append(c)

        invitation.countries.set(countries)
    return res 
示例#5
0
    def done(self, request, form_dict):
        try:
            for path, forms in form_dict.iteritems():
                for name, form in forms.iteritems():
                    if name == 'initial_ep':
                        #create election instance
                        self.ep_data = form.cleaned_data
                    else:
                        if not hasattr(self, 'profile_data'):
                            self.profile_data = {}
                        cleaned_data = form.cleaned_data
                        for key, value in cleaned_data['name'].iteritems():
                            cleaned_data[key] = value
                        del cleaned_data['name']
                        self.profile_data.update(cleaned_data)

            party = Party.objects.create(
                region=self.election_instance.council.region,
                level=self.election_instance.council.level,
                name=self.ep_data['name'],
                abbreviation=self.ep_data['abbreviation'])

            eip = ElectionInstanceParty.objects.create(
                party=party,
                election_instance=self.election_instance,
                position=self.ep_data['position'])
            # list_length=self.ep_data['list_length'])

            #Create the profile
            created, profile = create_profile('party_admin', self.profile_data)
            #Link the profile to the party
            party.contacts.add(profile.user)

            #Create the invitation
            templates = profile_invite_email_templates('party_admin')

            #TODO: change invitation text based on created
            Invitation.create(
                user_from=request.user,
                user_to=profile.user,
                view=reverse('bo.party_contact_wizard', kwargs={'id': eip.pk}),
                text=
                '<p>U bent aangekomen op de beheerderpagina van Wiekiesjij. Om Wiekiesjij gereed te maken voor uw partij volgen er nu een aantal schermen waarin u informatie kunt achterlaten. Wanneer deze informatie is ingevuld zullen we overgaan tot het uitnodigen van de kandidaten van uw partij.</p><p>We beginnen met het instellen van een wachtwoord voor Wiekiesjij door op <strong>Accepteer uitnodiging</strong> te klikken. Heeft u al eens eerder gebruik gemaakt van Wiekiesjij, drukt u dan op <strong>Ik heb al een account</strong>.</p><p>Om het gereedmaken van Wiekiesjij zo gemakkelijk mogelijk te laten verlopen hebben we een snelle start [link] handleiding [/link] beschikbaar gesteld die u kunt raadplegen.</p>',
                subject=ugettext('Invitation Wiekiesjij'),
                html_template=templates['html'],
                plain_template=templates['plain'],
            )

        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        if request.POST.get('skip', None) is not None:
            return redirect('bo.election_instance_view',
                            id=self.election_instance.id)

        return redirect('bo.election_party_edit', id=eip.id)
示例#6
0
    def invitations(self, ):
        Invitation.create(email=self.email)
        invite = Invitation.objects.get(email=self.email)
        invite.inviter = self.request.user
        invite.save

        print('invite', invite)
        invite.save
        invite.send_invitation(self.request)
示例#7
0
 def setUp(cls):
     cls.user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
     cls.accepted_invite = Invitation.create('*****@*****.**')
     cls.accepted_invite.accepted = True
     cls.accepted_invite.save()
     Invitation.create('*****@*****.**')
示例#8
0
    def done(self, request, form_dict):
        try:
            for path, forms in form_dict.iteritems():
                for name, form in forms.iteritems():
                    if name == 'initial_ep':
                        #create election instance
                        self.ep_data = form.cleaned_data
                    else:
                        if not hasattr(self, 'profile_data'):
                            self.profile_data = {}
                        cleaned_data = form.cleaned_data
                        for key, value in cleaned_data['name'].iteritems():
                            cleaned_data[key] = value
                        del cleaned_data['name']
                        self.profile_data.update(cleaned_data)  

            party = Party.objects.create(
                region = self.election_instance.council.region,
                level = self.election_instance.council.level,
                name = self.ep_data['name'],
                abbreviation = self.ep_data['abbreviation'])

            eip = ElectionInstanceParty.objects.create(
                party=party,
                election_instance=self.election_instance,
                position=self.ep_data['position'])
                # list_length=self.ep_data['list_length'])

            #Create the profile
            created, profile = create_profile('party_admin', self.profile_data)
            #Link the profile to the party
            party.contacts.add(profile.user)

            #Create the invitation
            templates = profile_invite_email_templates('party_admin')
            
            #TODO: change invitation text based on created
            Invitation.create(
                user_from=request.user,
                user_to=profile.user,
                view=reverse('bo.party_contact_wizard', kwargs={'id': eip.pk}),
                text='<p>U bent aangekomen op de beheerderpagina van Wiekiesjij. Om Wiekiesjij gereed te maken voor uw partij volgen er nu een aantal schermen waarin u informatie kunt achterlaten. Wanneer deze informatie is ingevuld zullen we overgaan tot het uitnodigen van de kandidaten van uw partij.</p><p>We beginnen met het instellen van een wachtwoord voor Wiekiesjij door op <strong>Accepteer uitnodiging</strong> te klikken. Heeft u al eens eerder gebruik gemaakt van Wiekiesjij, drukt u dan op <strong>Ik heb al een account</strong>.</p><p>Om het gereedmaken van Wiekiesjij zo gemakkelijk mogelijk te laten verlopen hebben we een snelle start [link] handleiding [/link] beschikbaar gesteld die u kunt raadplegen.</p>',
                subject=ugettext('Invitation Wiekiesjij'),
                html_template=templates['html'],
                plain_template=templates['plain'],
                )

        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()
        
        if request.POST.get('skip', None) is not None:
            return redirect('bo.election_instance_view', id=self.election_instance.id)

        return redirect('bo.election_party_edit', id=eip.id)
示例#9
0
 def setUp(cls):
     cls.user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
     cls.accepted_invite = Invitation.create('*****@*****.**')
     cls.accepted_invite.accepted = True
     cls.accepted_invite.save()
     Invitation.create('*****@*****.**')
示例#10
0
 def setUpClass(cls):
     cls.invitation1 = Invitation.create('*****@*****.**')
     cls.invitation2 = Invitation.create('*****@*****.**')
     cls.invitation3 = Invitation.create('*****@*****.**')
     cls.invitation4 = Invitation.create('*****@*****.**')
     cls.invitation1.accepted = True
     cls.invitation1.save()
     cls.invitation2.sent = timezone.now() - datetime.timedelta(
         days=app_settings.INVITATION_EXPIRY + 1)
     cls.invitation2.save()
示例#11
0
 def setUpClass(cls):
     cls.invitation1 = Invitation.create('*****@*****.**')
     cls.invitation2 = Invitation.create('*****@*****.**')
     cls.invitation3 = Invitation.create('*****@*****.**')
     cls.invitation4 = Invitation.create('*****@*****.**')
     cls.invitation1.accepted = True
     cls.invitation1.save()
     cls.invitation2.sent = timezone.now() - datetime.timedelta(
         days=app_settings.INVITATION_EXPIRY + 1)
     cls.invitation2.save()
示例#12
0
 def setUp(cls):
     cls.accepted_invite = Invitation.create('*****@*****.**')
     cls.accepted_invite.accepted = True
     cls.accepted_invite.save()
     pending_invite = Invitation.create('*****@*****.**')
     pending_invite.sent = timezone.now() - datetime.timedelta(
         days=app_settings.INVITATION_EXPIRY - 1)
     pending_invite.save()
     cls.existing_user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
示例#13
0
 def setUp(cls):
     cls.accepted_invite = Invitation.create('*****@*****.**')
     cls.accepted_invite.accepted = True
     cls.accepted_invite.save()
     pending_invite = Invitation.create('*****@*****.**')
     pending_invite.sent = timezone.now() - datetime.timedelta(
         days=app_settings.INVITATION_EXPIRY - 1)
     pending_invite.save()
     cls.existing_user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
示例#14
0
    def setUpClass(cls):
        cls.user = get_user_model().objects.create_user(username='******',
                                                        password='******')
        cls.invitation = Invitation.create('*****@*****.**',
                                           inviter=cls.user)
        cls.invitation.sent = timezone.now()
        cls.invitation.save()

        cls.accepted_invitation = Invitation.create('*****@*****.**',
                                                    inviter=cls.user)
        cls.accepted_invitation.sent = timezone.now()
        cls.accepted_invitation.accepted = True
        cls.accepted_invitation.save()
示例#15
0
    def setUpClass(cls):
        cls.user = get_user_model().objects.create_user(
            username='******',
            password='******')
        cls.invitation = Invitation.create(
            '*****@*****.**', inviter=cls.user)
        cls.invitation.sent = timezone.now()
        cls.invitation.save()

        cls.accepted_invitation = Invitation.create(
            '*****@*****.**', inviter=cls.user)
        cls.accepted_invitation.sent = timezone.now()
        cls.accepted_invitation.accepted = True
        cls.accepted_invitation.save()
示例#16
0
def create_invitation(request):
    if request.method == 'POST':
        serializer = InvitationSerializer(data=request.data)
        if serializer.is_valid():
            author = serializer.validated_data.get('author')
            email = serializer.validated_data.get('email')
            author_slug = author.get('slug')
            author_name = author.get('name')
            invite = Invitation.create(email=email, inviter=request.user)
            author_instance = None
            if author_slug:
                try:
                    author_instance = Author.objects.get(slug=author_slug)
                    author_instance.invite = invite
                    author_instance.save()
                except ObjectDoesNotExist:
                    pass

            if author_instance is None:
                author_instance = Author.objects.create(name=author_name,
                                                        invite=invite)

            invite.send_invitation(request)
            response_serializer = InvitationSerializer(invite)
            return Response(response_serializer.data,
                            status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    else:
        serializer = InvitationSerializer()
        return Response(serializer.data, status=status.HTTP_200_OK)
示例#17
0
    def invite_user(self,
                    from_user,
                    to_email,
                    role=BaseMembership.ROLE_MEMBER,
                    message=None):

        if Invitation.objects.filter(signup_code__email=to_email).exists():
            raise ValidationError(
                'The email address you entered has already been invited to join a team.'
            )
        try:
            if User.objects.get(email=to_email):
                raise ValidationError('This user is already apart of a team.')
        except User.DoesNotExist:
            # Send an invite if there is not an email address associated with that user
            invite = Invitation.invite(from_user,
                                       to_email,
                                       message,
                                       send=False)
            membership, created = self.memberships.get_or_create(
                invitation=invite,
                defaults={
                    "role": role,
                    "state": BaseMembership.STATE_INVITED
                })
            invite.send_invite()
            signals.invited_user.send(sender=self, membership=membership)
            return membership
示例#18
0
 def post(self, request, format=None):
     emails = list(set(request.data))
     # response = {'valid': [], 'invalid': []}
     response = list()
     for email in emails:
         email = email.strip()
         try:
             validate_email(email)
             CleanEmailMixin().validate_invitation(email)
             invite = Invitation.create(email)
         except (ValueError, KeyError):
             pass
         except (ValidationError):
             pass
             # response['invalid'].append({email: 'invalid email'})
         except (AlreadyAccepted):
             pass
             # response['invalid'].append({email: 'already accepted'})
         except (AlreadyInvited):
             pass
             # response['invalid'].append({email: 'pending invite'})
         except (UserRegisteredEmail):
             pass
             # response['invalid'].append({email: 'user registered email'})
         else:
             # invite.send_invitation(request)
             response.append(invite)
     serializer = self.serializer_class(response, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)
示例#19
0
def invitations(request, current_transaction):
    candidates = Candidate.objects.filter(transaction=current_transaction)
    if request.method == 'POST':
        if candidates.count() != 0:
            for candidate in candidates:
                if User.objects.filter(email=candidate.email).exists():
                    existinguser = User.objects.get(email=candidate.email)
                    send_mail(
                        'Test invitation',
                        'Hello' + ' ' + existinguser.first_name + ' ' +
                        existinguser.last_name + ' ' +
                        'you have been invited by a Recruiter to partake in a test. '
                        'Use this link to login and access the test invite under Invites: http://beta.codeln.com/accounts/login/',
                        '*****@*****.**',
                        [existinguser.email],
                        fail_silently=False,
                    )
                else:
                    invite = Invitation.create(candidate.email,
                                               inviter=request.user)
                    invite.send_invitation(request)

                current_transaction.stage = 'complete'
                current_transaction.save()
        elif candidates.count() == 0:
            current_transaction.stage = 'complete'
            current_transaction.save()
        return redirect(
            reverse('transactions:process_transaction',
                    args=[current_transaction.id]))
    return render(request, 'transactions/invitations.html', {
        'candidates': candidates,
        'current_transaction': current_transaction
    })
示例#20
0
 def setUpClass(cls):
     cls.user = get_user_model().objects.create_user(
         username='******',
         password='******')
     cls.invitation = Invitation.create(
         '*****@*****.**', inviter=cls.user)
     cls.adapter = get_invitations_adapter()
示例#21
0
文件: views.py 项目: sz-lhl/moear
    def post(self, request, format=None):
        '''
        用例::

            {
                "email": "*****@*****.**"
            }
        '''
        email = request.data.get('email', None)
        log.info('email: {}'.format(email))
        if not email:
            return Response(_('email 字段为空'),
                            status=status.HTTP_400_BAD_REQUEST)
        f = forms.EmailField()
        try:
            email = f.clean(email)
        except ValidationError as e:
            return Response(_('Email 值错误:{}'.format(', '.join(e))),
                            status=status.HTTP_400_BAD_REQUEST)
        try:
            invite = Invitation.create(email, inviter=self.request.user)
            invite.save()
            invite.send_invitation(self.request)
        except Exception as e:
            return Response(e, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response(_('已发送注册邀请邮件到【{email}】').format(email=email),
                        status=status.HTTP_200_OK)
示例#22
0
 def setUp(cls):
     cls.user = get_user_model().objects.create_user(username='******',
                                                     password='******')
     cls.existing_user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
     cls.invitation = Invitation.create('*****@*****.**')
 def test_send_invitation(self, db, rf, mailoutbox):
     invite = Invitation.create('{0}@example.com'.format(
         randint(11111111, 99999999)))
     mails_before = len(mailoutbox)
     invite.send_invitation(rf.get(''))
     assert len(mailoutbox) == mails_before + 1
     assert invite.key in mailoutbox[-1].body
     invite.delete()
示例#24
0
 def setUp(cls):
     cls.user = get_user_model().objects.create_user(
         username='******',
         password='******')
     cls.existing_user = get_user_model().objects.create_user(
         username='******',
         password='******',
         email='*****@*****.**')
     cls.invitation = Invitation.create('*****@*****.**')
示例#25
0
def dispatchInvitation(invitation: Invitation) -> bool:
    """
    Sends an email to an invitee
    """
    try:
        assert not invitation.mailed and not invitation.fulfilled
    except AssertionError:
        logger.warning(f"Invitation for {invitation.email} was not sent: "
                       "Already fulfilled!")
        return False

    if invitation.refkey is None:
        invitation.refkey = referralKeygen(invitation.email)
        invitation.save()

    if invitation.customemail and invitation.customsig:
        et = EmailTemplate(
            subject=settings.DEFAULT_EMAIL_TITLE,
            headline="Conflict Cartographer",
            message=invitation.customemail,
            signature=invitation.customsig,
        )
    else:
        try:
            et = EmailTemplate.objects.get(active=True, email_type="inv")
        except EmailTemplate.DoesNotExist:
            et = EmailTemplate.objects.create(
                active=True,
                subject=settings.DEFAULT_EMAIL_TITLE,
                email_type="inv")

    html = renderEmailTemplate(et, {"link": invitation.invitationLink()})
    plaintext = re.sub("\[[^\)]+", invitation.invitationLink(), et.message)

    call = {
        "subject": et.subject,
        "message": plaintext,
        "html_message": html,
        "from_email": settings.EMAIL_FROM_ADDRESS,
        "recipient_list": [invitation.email]
    }

    try:
        mail.send_mail(**call)
    except ConnectionRefusedError:
        logger.error("Failed to send email to %s, connection refused!",
                     invitation.email)
        return False
    else:
        logger.info("Sent email to %s", invitation.email)
        invitation.mailed = True
        invitation.save()
        return True
示例#26
0
def invitations_save(request):
	if request.method == 'POST':
		datos = json.loads(request.body.decode())

		invitacion = Invitation(username=request.user,invitacion=datos['data']['invitacion'])
		print(datos['data']['invitados'][0]['email'])
		invitacion.save()

		contenido = "Tu amigo "+request.user.first_name+" "+request.user.last_name+" te ha invitado a jugar la quiniela del mundial"
		contenido+= "en http://www.futbolgamb.com no dejes de entrar y divertirte tratando de asertar los resultados de los partidos y compitiendo contra otros"
		correos = []	

		for email in datos['data']['invitados']:
			correos.append(email['email'])

		send_mail('Invitaciones para futbolgamb', contenido, '*****@*****.**',correos, fail_silently=False)
		#return Response(position)
		#jsonResponse = serializers.serialize("json", position)
		return HttpResponse(json.dumps({"success" : "true"}), content_type="application/json",status=200)
    def test_delete_invitation(self):
        invitation = Invitation.create(email=f"{uuid4()}@{uuid4()}.com",
                                       inviter=self.user)
        invitation.save()

        self.client.login(username="******", password="******")
        self.login_2fa()

        response = self.client.get(
            reverse("invitation_delete", kwargs={"pk": invitation.id}))
        self.assertEqual(response.status_code, 200)
示例#28
0
 def activate(self, request):
     try:
         related_user = self.execute()
         message = f"added user {related_user} to {self.related_object}'s {self.relation_name}"
         messages.add_message(request, messages.SUCCESS, message)
     except User.DoesNotExist:
         self.save()
         Invitation.objects.filter(email=self.email).delete()
         invite = Invitation.create(self.email)
         invite.send_invitation(request)
         message = f"sent invite to {self.email}; upon signup the resulting user will be added to {self.related_object}'s {self.relation_name}"
         messages.add_message(request, messages.SUCCESS, message)
示例#29
0
def invitations(request, current_transaction):
    candidates = Candidate.objects.filter(transaction=current_transaction)
    if request.method == 'POST':
        if candidates.count() != 0:
            for candidate in candidates:
                invite = Invitation.create(candidate.email, inviter=request.user)
                invite.send_invitation(request)
            current_transaction.stage = 'complete'
            current_transaction.save()
        return redirect(reverse('transactions:process_transaction', args=[current_transaction.id]))
    return render(request, 'transactions/invitations.html',
                  {'candidates': candidates, 'current_transaction': current_transaction})
示例#30
0
 def save(self, *args, **kwargs):
     cleaned_data = super().clean()
     email = cleaned_data.get("email")
     params = {
         "email": email,
         "inviter": self.request.user,
     }
     instance = Invitation.create(**params)
     instance.send_invitation(self.request, language=get_language())
     # We can't call InvitationAdminForm here, it would try to send 2 invitations
     super(forms.ModelForm, self).save(*args, **kwargs)
     return instance
    def test_invitation_deleted(self):
        self.login()
        user_credentials = get_other_credentials()
        Invitation.create(email=user_credentials.get("email"),
                          inviter=self.user)
        user = User.objects.create_user(**user_credentials)

        # Delete the user with an existing invitation
        response = self.client.post(
            reverse("user_delete", kwargs={"pk": user.id}))
        self.assertRedirects(response, reverse("profiles"))

        count = Invitation.objects.filter(
            email=user_credentials.get("email")).count()
        self.assertEqual(count, 0)

        # Try to delete the user without invitation
        user = User.objects.create_user(**user_credentials)
        response = self.client.post(
            reverse("user_delete", kwargs={"pk": user.id}))
        self.assertRedirects(response, reverse("profiles"))
示例#32
0
def sendMail(email, user):
    if isValidEmail(email):
        if user.profile.remaining_invitations <= 0:
            return False
        token = uuid.uuid1().hex
        link = settings.WEB_URL + "/register?email=" + email + "&token=" + token + "&id=" + str(
            user.id)
        message = u'¡Nuestro usuario ' + user.first_name + u' ' + user.last_name + u' quiere trocar contigo! ¡Únete a esta gran comunidad que recicla e intercambia sin dinero! \n \n Sólo ingresa a \n' + link
        subject = user.first_name + u' te invitó Trueque'
        #        send_mail( subject, message, settings.EMAIL_HOST_USER, [email], fail_silently=False)
        print message
        inv = Invitation(id_sender=user,
                         email=email,
                         token=token,
                         pending=True)
        inv.save()
        profile = user.profile
        profile.remaining_invitations = profile.remaining_invitations - 1
        puntos = Point.objects.get(action="invitation_sent")
        profile.quds = profile.quds + puntos.qty
        profile.save()
        return True
    def test_delete_invitation_normal_user(self):
        invitation = Invitation.create(email=f"{uuid4()}@{uuid4()}.com",
                                       inviter=self.user)
        invitation.save()

        other_credentials = get_other_credentials(is_admin=False)
        other_user = User.objects.create_user(**other_credentials)
        self.client.login(username=other_user.email,
                          password=other_credentials.get("password"))
        self.login_2fa(other_user)

        response = self.client.get(
            reverse("invitation_delete", kwargs={"pk": invitation.id}))
        self.assertEqual(response.status_code, 403)
    def test_see_invitations_list_with_expired_invite(self):
        invitation = Invitation.create(email=f"{uuid4()}@{uuid4()}.com",
                                       inviter=self.user)
        # Invitations expire after 24 hours
        invitation.sent = timezone.now() + timezone.timedelta(hours=-25)
        invitation.save()

        self.client.login(username="******", password="******")
        self.login_2fa()

        response = self.client.get(reverse("invitation_list"))
        self.assertContains(response, "<td>{}</td>".format(invitation.email))
        self.assertContains(response,
                            "<strong class='tag tag--red'>Expired</strong>",
                            html=True)
    def test_see_invitations_list_with_pending_invite(self):
        invitation = Invitation.create(email=f"{uuid4()}@{uuid4()}.com",
                                       inviter=self.user)
        # If we dont send the invitation, we need to fake a sent date
        invitation.sent = timezone.now()
        invitation.save()

        self.client.login(username="******", password="******")
        self.login_2fa()

        response = self.client.get(reverse("invitation_list"))
        self.assertContains(response, "<td>{}</td>".format(invitation.email))
        self.assertContains(response,
                            "<strong class='tag tag--blue'>Pending</strong>",
                            html=True)
    def test_sent_invite_again_if_accepted_invite_exists_and_user_account_exists(
        self, ):
        """
        Login and send a duplicate invite where another invite already exists
        and there is a user account corresponding to the invited email address
        """
        other_credentials = get_other_credentials(is_admin=False)
        User.objects.create_user(**other_credentials)
        Invitation.create(
            other_credentials["email"],
            inviter=self.user,
            sent=timezone.now(),
            accepted=True,
        )

        self.client.login(username="******", password="******")
        self.login_2fa()
        response = self.client.post(reverse("invite"),
                                    {"email": other_credentials["email"]},
                                    follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertContains(
            response, "This email address already has a portal account.")
示例#37
0
 def setUp(self):
     super().setUp(is_admin=False)
     self.inviter_credentials = {
         "email": "*****@*****.**",
         "name": "InviterUser",
         "province": HealthcareProvince.objects.get(abbr="MB"),
         "is_admin": True,
         "password": "******",
         "phone_number": "+12125552368",
     }
     self.inviter = User.objects.create_user(**self.inviter_credentials)
     self.invite = Invitation.create(self.user.email,
                                     inviter=self.inviter,
                                     sent=timezone.now())
     self.invite.accepted = True
    def setUp(self):
        super().setUp()
        self.invite = Invitation.create(self.invited_email,
                                        inviter=self.user,
                                        sent=timezone.now())

        password = uuid4()
        self.new_user_data = {
            "email": self.invited_email,
            "province": "CDS",
            "name": "Chuck Norris",
            "phone_number": "+12125552368",
            "phone_number_confirmation": "+12125552368",
            "password1": password,
            "password2": password,
        }
    def test_redirect_to_login_with_expired_message_on_expired_invite(self):
        invitation = Invitation.create(email="*****@*****.**",
                                       inviter=self.user)
        # Invitations expire after 24 hours
        invitation.sent = timezone.now() + timezone.timedelta(hours=-25)
        invitation.save()

        url = reverse("invitations:accept-invite",
                      kwargs={"key": invitation.key})

        response = self.client.post(url, follow=True)
        self.assertEqual(response.request["PATH_INFO"], "/en/invite/expired")
        self.assertContains(
            response,
            "<h1>You need a new link to create an account</h1>",
            html=True,
        )
示例#40
0
 def save(self, user_id):
     return Invitation.create(email=self.instance.email, user_id=user_id)
示例#41
0
    def done(self, request, form_dict):

        try:
            for path, forms in form_dict.iteritems():
                for name, form in forms.iteritems():
                    if name == 'initial_form':
                        self.form_data = form.cleaned_data
                    else:
                        if not hasattr(self, 'form_data'):
                            self.form_data = {}
                        self.form_data.update(form.cleaned_data)
            
            
            #Store data
            tmp_data = {
                'first_name': self.form_data['name']['first_name'],
                'middle_name': self.form_data['name']['middle_name'],
                'last_name': self.form_data['name']['last_name'],
                'email': self.form_data['email'],
                'gender': self.form_data['gender'],
            }
            created, self.candidate = create_profile('candidate', tmp_data)
            
            # If it's an existing user and (s)he is already in this party as candidate we won't allow it
            if not created and Candidacy.objects.filter(election_party_instance__pk=self.election_instance_party_id, candidate=self.candidate.user).count() != 0:
                request.user.message_set.create(message=ugettext('Elke kandidaat van een partij moet een uniek e-mail adres hebben.'))
                #We need to commit the transaction, even if we didn't do anything, or the transaction manager will throw an error
                transaction.commit()
                return redirect('bo.election_party_view', self.election_instance_party_id)
                

            #Link candidate to party
            candidacy = Candidacy(
                election_party_instance = get_object_or_404(ElectionInstanceParty, pk=self.election_instance_party_id),
                candidate = self.candidate.user,
                position = self.position,
            )
            candidacy.save()

            #Create invitation
            templates = profile_invite_email_templates('candidate')
            
            #TODO: change invitation text based on created
            
            Invitation.create(
                user_from = request.user,
                user_to = self.candidate.user,
                view = reverse('bo.politician_welcome', kwargs={'eip_id': self.eip.id}),
                text = '<p>Wiekiesjij is de voorkeurstemhulp van Nederland. Middels het beantwoorden een vijftiental vragen zullen bezoekers gekoppeld worden aan hun favoriete kandidaten. Middels de informatie die u hier invult zullen wij daarnaast in staat zijn om de bezoekers de mogelijkheid te bieden om te browsen tussen alle kandidaten, de partijen en is het mogelijk om de uitgebreide profielen van alle politici te bekijken.</p>',
                subject = ugettext('Invitation Wiekiesjij'),
                html_template = templates['html'],
                plain_template = templates['plain'],
            )

        except Exception:
            transaction.rollback()
            raise
        else:
            transaction.commit()

        return redirect('bo.election_party_view', self.election_instance_party_id)
示例#42
0
def csv_import_candidates_step3(request, ep_id):
    check_permissions(request, ep_id, 'party_admin')
    eip_obj = get_object_or_404(ElectionInstanceParty, pk=ep_id)
    try:
        positions = Candidacy.objects.filter(election_party_instance=eip_obj).values_list('position', flat=True)
        candidate_emails = Candidacy.objects.filter(election_party_instance=eip_obj).values_list('candidate__email', flat=True)
        candidates = functions.get_candidates_from_csv(request.session, positions, candidate_emails)
    except:

        path = settings.TMP_ROOT + '/'
        if not os.path.isdir(path):
            os.remove(path + request.session['csv_candidate_filename'])
        request.session['csv_candidate_filename'] = ''
        return redirect('bo.csv_candidates_step2', ep_id=ep_id, error='true')

    if request.method == 'POST':
        form = CsvConfirmForm(request.POST)
        if form.is_valid():
            for candidate in candidates.values():
                try:
                    #Store data
                    tmp_data = {
                        'first_name': candidate['first_name'],
                        'middle_name': candidate['middle_name'],
                        'last_name': candidate['last_name'],
                        'initials': candidate['initials'],
                        'email': candidate['email'],
                        'gender': candidate['gender'],
                    }
                    created, candidate_obj = create_profile('candidate', tmp_data)

                    if candidate_obj is None:
                        continue

                    #Link candidate to party
                    Candidacy.objects.create(
                        election_party_instance = eip_obj,
                        candidate = candidate_obj.user,
                        position = candidate['position'],
                    )

                    #Create invitation TODO: view and text etc.
                    templates = profile_invite_email_templates('candidate')
                    Invitation.create(
                        user_from = request.user,
                        user_to = candidate_obj.user,
                        view = reverse('bo.politician_welcome', kwargs={'eip_id': eip_obj.id}),
                        text = '<p>Wiekiesjij is de voorkeurstemhulp van Nederland. Middels het beantwoorden een vijftiental vragen zullen bezoekers gekoppeld worden aan hun favoriete kandidaten. Middels de informatie die u hier invult zullen wij daarnaast in staat zijn om de bezoekers de mogelijkheid te bieden om te browsen tussen alle kandidaten, de partijen en is het mogelijk om de uitgebreide profielen van alle politici te bekijken.</p>',
                        subject = ugettext('Invitation Wiekiesjij'),
                        html_template = templates['html'],
                        plain_template = templates['plain'],
                    )

                    position = int(candidate['position'])
                    if position > eip_obj.list_length:
                        eip_obj.list_length = position
                        eip_obj.save()

                except:
                    transaction.rollback()
                    raise

            transaction.commit()
            os.remove(settings.TMP_ROOT + '/' + request.session['csv_candidate_filename'])
            request.session['csv_candidate_filename'] = ''
            return redirect('bo.election_party_view', id=ep_id)
    else:
        form = CsvConfirmForm()
    eip = get_object_or_404(ElectionInstanceParty, pk=ep_id)
    forms = dict({'csv_confirm': form})
    return render_to_response('backoffice/csv_candidates_3.html', {'candidates':candidates, 'forms':forms, 'ep_id':ep_id, 'instance':eip.election_instance}, context_instance=RequestContext(request))
示例#43
0
def csv_import_parties_step3(request, ei_id):
    check_permissions(request, ei_id, 'council_admin')
    ei_obj = get_object_or_404(ElectionInstance, pk=ei_id)
    try:
        lists = ElectionInstanceParty.objects.filter(election_instance=ei_obj).values_list('position', flat=True)
        parties = functions.get_parties_from_csv(request.session, lists)
    except:
        path = settings.TMP_ROOT + '/'
        if not os.path.isdir(path):
            os.remove(path + request.session['csv_party_filename'])
        request.session['csv_party_filename'] = ''
        return redirect('bo.csv_parties_step2', ei_id = ei_id, error='true')

    if request.method == 'POST':
        form = CsvConfirmForm(request.POST)
        if form.is_valid():

            council = ei_obj.council
            region = council.region
            level = council.level

            for party in parties.values():
                try:
                    #Store data
                    tmp_data = {
                        'first_name': party['contact_first_name'],
                        'middle_name': party['contact_middle_name'],
                        'last_name': party['contact_last_name'],
                        'email': party['contact_email'],
                        'gender': party['contact_gender'],
                    }
                    created, contact = create_profile('party_admin', tmp_data)

                    if contact is None:
                        continue

                    party_obj = Party.objects.create(
                        region = region,
                        level = level,
                        name = party['name'],
                        abbreviation = party['abbreviation'],
                    )

                    eip_obj = ElectionInstanceParty.objects.create(
                        election_instance = ei_obj,
                        party = party_obj,
                        position = unicode(party['list']),
                        list_length = 10, #TODO, maybe add in CSV
                    )

                    party_obj.contacts.add(contact.user)
                    party_obj.save()

                    #Create invitation
                    templates = profile_invite_email_templates('party_admin')
                    Invitation.create(
                        user_from = request.user,
                        user_to = contact.user,
                        view=reverse('bo.party_contact_wizard', kwargs={'id': eip_obj.pk}),
                        text='<p>U bent aangekomen op de beheerderpagina van Wiekiesjij. Om Wiekiesjij gereed te maken voor uw partij volgen er nu een aantal schermen waarin u informatie kunt achterlaten. Wanneer deze informatie is ingevuld zullen we overgaan tot het uitnodigen van de kandidaten van uw partij.</p><p>We beginnen met het instellen van een wachtwoord voor Wiekiesjij door op <strong>Accepteer uitnodiging</strong> te klikken. Heeft u al eens eerder gebruik gemaakt van Wiekiesjij, drukt u dan op <strong>Ik heb al een account</strong>.</p><p>Om het gereedmaken van Wiekiesjij zo gemakkelijk mogelijk te laten verlopen hebben we een snelle start [link] handleiding [/link] beschikbaar gesteld die u kunt raadplegen.</p>',
                        subject = ugettext('Invitation Wiekiesjij'),
                        html_template = templates['html'],
                        plain_template = templates['plain'],
                    )

                    max_list = int(party['list'])
                    if max_list > ei_obj.num_lists:
                        ei_obj.num_lists = max_list
                        ei_obj.save()

                except:
                    transaction.rollback()
                    raise
                else:
                    transaction.commit()

            os.remove(settings.TMP_ROOT + '/' + request.session['csv_party_filename'])
            request.session['csv_party_filename'] = ''
            return redirect('bo.election_instance_view', id=ei_id)
    else:
        form = CsvConfirmForm()
    ei_obj = get_object_or_404(ElectionInstance, id=ei_id)
    forms = dict({'csv_confirm': form})
    return render_to_response('backoffice/csv_parties_3.html', {'parties':parties, 'forms':forms, 'ei_id': ei_id, 'instance':ei_obj}, context_instance=RequestContext(request))
示例#44
0
 def setUpClass(cls):
     freezer = freeze_time('2015-07-30 12:00:06')
     freezer.start()
     cls.invitation = Invitation.create('*****@*****.**')
     freezer.stop()
示例#45
0
 def setUp(cls):
     cls.user = get_user_model().objects.create_user(
         username='******', password='******')
     cls.invite = Invitation.create(
         email='*****@*****.**', inviter=cls.user)
示例#46
0
 def done(self, request, form_dict):
     """
         Called after all steps are done
     """
     try:
         # This needs to be easier !?!
         for path, forms in form_dict.iteritems():
             for name, form in forms.iteritems():
                 if name == 'initial_ei':
                     self.ei_data = form.cleaned_data
                 else:
                     if not hasattr(self, 'profile_data'):
                         self.profile_data = {}
                     cleaned_data = form.cleaned_data
                     for key, value in cleaned_data['name'].iteritems():
                         cleaned_data[key] = value
                     del cleaned_data['name']
                     self.profile_data.update(cleaned_data)
     
         #Get the election event
         ee = ElectionEvent.objects.get(pk=settings.ELECTION_EVENT_ID)
         
         #Create the council
         council = Council.objects.create(
             name=ugettext('Council of %(name)s') % {'name': self.ei_data['name']},
             region=self.ei_data['region'],
             level=self.ei_data['level']
         )
         #Create the election instance
         ei = ElectionInstance.objects.create(
             name=self.ei_data['name'],
             council=council,
             election_event=ee,
             num_lists=1,
             start_date=datetime.datetime.now(),
             end_date=datetime.datetime.now(),
             wizard_start_date=datetime.datetime.now(),
         )
         #Create the profile
         created, profile = create_profile('council_admin', self.profile_data)
         
         #Link the profile to the council
         council.chanceries.add(profile.user)
         
         ei.modules.clear()
         ei.modules = self.ei_data['modules']
         
         
         questionset = self.ei_data['question_set']
         
         if questionset:
             for qsq in questionset.questionsetquestion_set.order_by('position'):
                 ElectionInstanceQuestion.objects.create(
                     election_instance = ei,
                     position = qsq.position,
                     question=qsq.question,
                     locked=True,
                 )
             
         
         #Create the invitation
         templates = profile_invite_email_templates('council_admin')
         
         #TODO: Change invitation text based on created or not
         
         Invitation.create(
             user_from=request.user, 
             user_to=profile.user,
             view=reverse('bo.election_setup', kwargs={'election_instance_id': ei.pk}),
             text="<p>U bent aangekomen op de beheerderpagina van Wiekiesjij. Om Wiekiesjij gereed te maken voor uw verkiezingen volgen er nu een aantal schermen waarin u informatie kunt achterlaten. Wanneer deze informatie is ingevuld zullen we overgaan tot het uitnodigen van de partijen die zullen participeren in deze verkiezingen.</p><p>We beginnen met het instellen van een wachtwoord voor Wiekiesjij door op <strong>Accepteer uitnodiging</strong> te klikken. Heeft u al eens eerder gebruik gemaakt van Wiekiesjij, drukt u dan op <strong>Ik heb al een account</strong>.</p><p>Om het gereedmaken van Wiekiesjij zo gemakkelijk mogelijk te laten verlopen hebben we een snelle start [link]handleiding[/link] beschikbaar gesteld die u kunt raadplegen.</p>",
             subject=ugettext('Invitation Wiekiesjij'),
             html_template=templates['html'],
             plain_template=templates['plain'],
             )
         
     except Exception:
         transaction.rollback()
         raise
     else:
         transaction.commit()
     
     if request.POST.get('skip', None) is not None:
         return redirect('bo.election_event')
     
     return redirect('bo.edit_council', id=ei.id)