Exemplo n.º 1
0
    def finalizeInvoice(self):
        # This will close out this invoice for editing, and also
        # generate the actual PDF

        # Calculate the total
        total = Decimal(0)
        totalvat = Decimal(0)
        for r in self.invoice.invoicerow_set.all():
            total += r.rowamount * r.rowcount
            totalvat += r.totalvat
        totalvat = totalvat.quantize(Decimal('.01'))  # Round off to two digits
        self.invoice.total_amount = total + totalvat
        self.invoice.total_vat = totalvat

        if self.invoice.reverse_vat and self.invoice.total_vat > 0:
            raise Exception("Can't have both reverse VAT and a non-zero VAT!")

        # Generate a secret key that can be used to view the invoice if
        # there is no associated account
        self.invoice.recipient_secret = generate_random_token()

        # Generate pdf
        self.invoice.pdf_invoice = base64.b64encode(self.render_pdf_invoice()).decode('ascii')

        # Indicate that we're finalized
        self.invoice.finalized = True

        # And we're done!
        self.invoice.save()
        InvoiceHistory(invoice=self.invoice, txt='Finalized').save()
Exemplo n.º 2
0
def meeting_proxy(request, meetingid):
    # Assign proxy voter for meeting
    meeting = get_object_or_404(Meeting, pk=meetingid)
    member = get_object_or_404(Member, user=request.user)

    if not (member.paiduntil and member.paiduntil >= datetime.today().date()):
        return HttpResponse("Your membership is not active")

    if not meeting.allmembers:
        if not meeting.members.filter(pk=member.pk).exists():
            return HttpResponse("Access denied.")

    if member.paiduntil < meeting.dateandtime.date():
        return HttpResponse("Your membership expires before the meeting")

    # Do we have one already?
    try:
        key = MemberMeetingKey.objects.get(member=member, meeting=meeting)
    except MemberMeetingKey.DoesNotExist:
        key = MemberMeetingKey()
        key.meeting = meeting
        key.member = member

    initial = {
        'name': key.proxyname,
    }

    if request.method == 'POST':
        form = ProxyVoterForm(initial=initial, data=request.POST)
        if form.is_valid():
            if form.cleaned_data['name']:
                key.proxyname = form.cleaned_data['name']
                key.proxyaccesskey = generate_random_token()
                key.key = base64.urlsafe_b64encode(
                    os.urandom(40)).rstrip(b'=').decode('utf8')
                key.save()
                MemberLog(member=member,
                          timestamp=datetime.now(),
                          message="Assigned {0} as proxy voter in {1}".format(
                              key.proxyname, meeting.name)).save()
                return HttpResponseRedirect('.')
            else:
                key.delete()
                MemberLog(member=member,
                          timestamp=datetime.now(),
                          message="Canceled proxy voting in {0}".format(
                              meeting.name)).save()
                return HttpResponseRedirect("../../")
    else:
        form = ProxyVoterForm(initial=initial)

    return render(request, 'membership/meetingproxy.html', {
        'member': member,
        'meeting': meeting,
        'key': key,
        'form': form,
    })
Exemplo n.º 3
0
def conference_temp_token(request, confname):
    redir = request.GET.get('redir', None)
    if not redir:
        return HttpResponse("Mandatory parameter missing", status=404)

    redir = urlparse(redir)

    # Create, or replace, a temporary token for this login, which can later be exchanged for a full JWT.
    conference = get_conference_or_404(confname)
    if not conference.key_public:
        return HttpResponse("Conference key not found", status=404)

    # Explicitly compare scheme/location/path, but *not* the querystring.
    if redir._replace(
            query=None,
            fragment=None).geturl() not in conference.web_origins.split(','):
        return HttpResponse("Forbidden redirect URL", status=403)

    try:
        reg = ConferenceRegistration.objects.get(conference=conference,
                                                 attendee=request.user)
    except ConferenceRegistration.DoesNotExist:
        return HttpResponse("You are not registered for this conference",
                            status=403,
                            content_type='text/plain')

    if not reg.payconfirmedat:
        return HttpResponse("Not confirmed for this conference",
                            status=403,
                            conten_type='text/plain')

    with transaction.atomic():
        # If there is an existing token for this user, just remove it.
        ConferenceRegistrationTemporaryToken.objects.filter(reg=reg).delete()

        # Create a new one
        t = ConferenceRegistrationTemporaryToken(
            reg=reg,
            token=generate_random_token(),
            expires=timezone.now() + timedelta(minutes=5),
        )
        t.save()

        reglog(reg, 'Issued temporary token', request.user)

        # If there are any parameters included in the redirect, we just append ours to it
        param = dict(parse_qsl(redir.query))
        param['token'] = t.token

        return HttpResponseRedirect(
            redir._replace(query=urlencode(param)).geturl())
Exemplo n.º 4
0
    def enable_webhook(self, request):
        token = generate_random_token()

        Telegram(self.instance.id, self.instance.config).post('setWebhook', {
            'url': '{}/wh/{}/{}/'.format(settings.SITEBASE, self.instance.id, token),
            'max_connections': 2,
            'allowed_updates': ['channel_post', 'message'],
        })
        self.instance.config['webhook'] = {
            'token': token,
        }
        self.instance.save(update_fields=['config'])

        messages.info(request, "Webhook has been enabled!")
        return True
Exemplo n.º 5
0
    def refresh_messaging_config(self, config):
        mod = False

        if 'channeltoken' not in config:
            config['channeltoken'] = {}
        if 'tokenchannel' not in config:
            config['tokenchannel'] = {}

        for channel in ['privatebcast', 'orgnotification']:
            if channel not in config['channeltoken']:
                # Create a token!
                t = generate_random_token()
                config['channeltoken'][channel] = t
                config['tokenchannel'][t] = channel
            mod = True
        return mod
Exemplo n.º 6
0
def sponsor_scanning(request, sponsorid):
    sponsor, is_admin = _get_sponsor_and_admin(sponsorid, request, False)

    if not sponsor.conference.askbadgescan:
        return HttpResponse(
            "Badge scanning questions are not enabled on this conference",
            status=403)

    if not SponsorClaimedBenefit.objects.filter(
            sponsor=sponsor,
            benefit__benefit_class=get_benefit_id(
                'badgescanning.BadgeScanning'),
            declined=False,
            confirmed=True).exists():
        return HttpResponse(
            "Badge scanning not a claimed benefit for this sponsor",
            status=403)

    if request.method == 'POST':
        if request.POST.get('what', '') == 'add':
            if not request.POST.get('email', ''):
                messages.warning(request, "Cannot add empty address")
                return HttpResponseRedirect(".")
            try:
                reg = ConferenceRegistration.objects.get(
                    conference=sponsor.conference,
                    email=request.POST.get('email').lower())
                if not reg.payconfirmedat:
                    messages.error(request, "Attendee is not confirmed")
                    return HttpResponseRedirect(".")
                if sponsor.sponsorscanner_set.filter(scanner=reg).exists():
                    messages.warning(
                        request, "Attendee already registered as a scanner")
                    return HttpResponseRedirect(".")
                scanner = SponsorScanner(sponsor=sponsor,
                                         scanner=reg,
                                         token=generate_random_token())
                scanner.save()
                sponsor.sponsorscanner_set.add(scanner)
                return HttpResponseRedirect(".")
            except ConferenceRegistration.DoesNotExist:
                messages.error(request, "Attendee not found")
                return HttpResponseRedirect(".")
        elif request.POST.get('what', '') == 'del':
            # There should only be one remove-<something>
            for k in request.POST.keys():
                if k.startswith('remove-'):
                    rid = k[len('remove-'):]
                    try:
                        scanner = SponsorScanner.objects.get(sponsor=sponsor,
                                                             pk=rid)
                        n = scanner.scanner.fullname
                        if scanner.scanner.scanned_attendees.exists():
                            messages.warning(
                                request,
                                "Attende {0} has scanned badges already, cannot be removed"
                                .format(n))
                        else:
                            scanner.delete()
                            messages.info(
                                request,
                                "Attendee {0} removed from scanning".format(n))
                    except SponsorScanner.DoesNotExist:
                        messges.error(request, "Attendee not found")
                    return HttpResponseRedirect(".")
                elif k.startswith('email-'):
                    rid = k[len('email-'):]
                    try:
                        scanner = SponsorScanner.objects.get(sponsor=sponsor,
                                                             pk=rid)
                        send_conference_mail(
                            sponsor.conference,
                            scanner.scanner.email,
                            "Attendee badge scanning",
                            "confsponsor/mail/badge_scanning_intro.txt",
                            {
                                'conference': sponsor.conference,
                                'sponsor': sponsor,
                                'scanner': scanner,
                            },
                            sender=sponsor.conference.sponsoraddr,
                            receivername=scanner.scanner.fullname,
                        )
                        messages.info(
                            request, "Instructions email sent to {0}".format(
                                scanner.scanner.fullname))
                    except SponsorScanner.DoesNotExist:
                        messages.error(request, "Attendee not found")
                    return HttpResponseRedirect(".")
            else:
                messages.error(request, "Invalid form submit")
                return HttpResponseRedirect(".")
        elif request.POST.get('what', '') == 'delscan':
            # There should only be one delete-scan-<id>
            for k in request.POST.keys():
                if k.startswith('delete-scan-'):
                    scid = int(k[len('delete-scan-'):])
                    try:
                        scan = ScannedAttendee.objects.get(sponsor=sponsor,
                                                           pk=scid)
                        scan.delete()
                    except ScannedAttendee.DoesNotExist:
                        messages.error(
                            request,
                            "Scan has already been removed or permission denied"
                        )
                    break
            else:
                messages.error(request, "Invalid form submit")
            return HttpResponseRedirect(".")
        else:
            # Unknown form, so just return
            return HttpResponseRedirect(".")

    scanned = ScannedAttendee.objects.select_related(
        'attendee', 'scannedby', 'attendee__country').filter(sponsor=sponsor)

    return render(request, 'confsponsor/sponsor_scanning.html', {
        'scanners': sponsor.sponsorscanner_set.all(),
        'scanned': scanned,
    })