Esempio n. 1
0
File: cart.py Progetto: rixx/pretix
    def dispatch(self, request, *args, **kwargs):
        from pretix.base.services.cart import error_messages

        err = None
        v = request.GET.get('voucher')

        if v:
            v = v.strip()
            try:
                self.voucher = Voucher.objects.get(code=v, event=request.event)
                if self.voucher.redeemed:
                    err = error_messages['voucher_redeemed']
                if self.voucher.valid_until is not None and self.voucher.valid_until < now():
                    err = error_messages['voucher_expired']
            except Voucher.DoesNotExist:
                err = error_messages['voucher_invalid']
        else:
            return redirect(eventreverse(request.event, 'presale:event.index'))

        if request.event.presale_start and now() < request.event.presale_start:
            err = error_messages['not_started']
        if request.event.presale_end and now() > request.event.presale_end:
            err = error_messages['ended']

        if err:
            messages.error(request, _(err))
            return redirect(eventreverse(request.event, 'presale:event.index'))

        return super().dispatch(request, *args, **kwargs)
Esempio n. 2
0
def test_event_custom_domain_cache(env):
    KnownDomain.objects.create(domainname='foobar', organizer=env[0])
    env[0].get_cache().clear()
    with assert_num_queries(1):
        eventreverse(env[1], 'presale:event.index')
    with assert_num_queries(0):
        eventreverse(env[1], 'presale:event.index')
Esempio n. 3
0
    def _redirect_to_order(self):
        if self.request.session.get('payment_stripe_order_secret') != self.order.secret:
            messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
                                           'in your emails to continue.'))
            return redirect(eventreverse(self.request.event, 'presale:event.index'))

        return redirect(eventreverse(self.request.event, 'presale:event.order', kwargs={
            'order': self.order.code,
            'secret': self.order.secret
        }) + ('?paid=yes' if self.order.status == Order.STATUS_PAID else ''))
Esempio n. 4
0
 def url(self):
     if isinstance(self.position, OrderPosition):
         return eventreverse(self.event, 'presale:event.order.download.answer', kwargs={
             'order': self.position.order.code,
             'secret': self.position.order.secret,
             'answer': self.answer.pk,
         })
     else:
         return eventreverse(self.event, 'presale:event.cart.download.answer', kwargs={
             'answer': self.answer.pk,
         })
Esempio n. 5
0
 def get_order_url(self, order):
     payment = order.payments.first()
     if not payment:
         return eventreverse(self.request.event, 'presale:event.order', kwargs={
             'order': order.code,
             'secret': order.secret,
         }) + '?thanks=1'
     return eventreverse(self.request.event, 'presale:event.order.pay.complete', kwargs={
         'order': order.code,
         'secret': order.secret,
         'payment': payment.pk
     })
Esempio n. 6
0
 def get_order_url(self, order):
     payment = order.payments.filter(state__in=[OrderPayment.PAYMENT_STATE_CREATED, OrderPayment.PAYMENT_STATE_PENDING]).first()
     if not payment:
         return eventreverse(self.request.event, 'presale:event.order', kwargs={
             'order': order.code,
             'secret': order.secret,
         }) + '?thanks=1'
     return eventreverse(self.request.event, 'presale:event.order.pay.complete', kwargs={
         'order': order.code,
         'secret': order.secret,
         'payment': payment.pk
     })
Esempio n. 7
0
def abort(request, *args, **kwargs):
    messages.error(request, _('It looks like you canceled the PayPal payment'))

    if request.session.get('payment_paypal_payment'):
        payment = OrderPayment.objects.get(pk=request.session.get('payment_paypal_payment'))
    else:
        payment = None

    if payment:
        return redirect(eventreverse(request.event, 'presale:event.order', kwargs={
            'order': payment.order.code,
            'secret': payment.order.secret
        }) + ('?paid=yes' if payment.order.status == Order.STATUS_PAID else ''))
    else:
        return redirect(eventreverse(request.event, 'presale:event.checkout', kwargs={'step': 'payment'}))
Esempio n. 8
0
def abort(request, organizer=None, event=None):
    messages.error(request, _('It looks like you cancelled the PayPal payment'))
    try:
        event = Event.objects.get(id=request.session['payment_paypal_event'])
        return redirect(eventreverse(event, 'presale:event.checkout', kwargs={'step': 'payment'}))
    except Event.DoesNotExist:
        pass  # TODO: Handle this
Esempio n. 9
0
def retry(request, order):
    try:
        order = Order.objects.current.get(
            user=request.user,
            code=order,
        )
    except Order.DoesNotExist:
        return  # TODO: Handle this

    provider = Paypal(order.event)
    provider.init_api()

    if 'token' in request.GET:
        if 'PayerID' in request.GET:
            payment = paypalrestsdk.Payment.find(request.session.get('payment_paypal_id'))
            provider._execute_payment(payment, request, order)
        else:
            messages.error(request, _('It looks like you cancelled the PayPal payment'))
    else:
        payment = paypalrestsdk.Payment({
            'intent': 'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url": build_absolute_uri('plugins:paypal:retry', kwargs={
                    'order': order.code
                }),
                "cancel_url": build_absolute_uri('plugins:paypal:retry', kwargs={
                    'order': order.code
                }),
            },
            "transactions": [
                {
                    "item_list": {
                        "items": [
                            {
                                "name": 'Order %s' % order.code,
                                "quantity": 1,
                                "price": str(order.total),
                                "currency": order.event.currency
                            }
                        ]
                    },
                    "amount": {
                        "currency": order.event.currency,
                        "total": str(order.total)
                    },
                    "description": __('Event tickets for %s') % order.event.name
                }
            ]
        })
        resp = provider._create_payment(request, payment)
        if resp:
            return redirect(resp)

    return redirect(eventreverse(order.event, 'presale:event.order', kwargs={
        'order': order.code,
        'secret': order.secret
    }) + '?paid=yes')
Esempio n. 10
0
    def render(self, context):
        from pretix.multidomain.urlreverse import eventreverse
        kwargs = {
            smart_text(k, 'ascii'): v.resolve(context)
            for k, v in self.kwargs.items()
        }
        view_name = self.view_name.resolve(context)
        event = self.event.resolve(context)
        url = ''
        try:
            if self.absolute:
                url = build_absolute_uri(event, view_name, kwargs=kwargs)
            else:
                url = eventreverse(event, view_name, kwargs=kwargs)
        except NoReverseMatch:
            if self.asvar is None:
                raise

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            if context.autoescape:
                url = conditional_escape(url)
            return url
Esempio n. 11
0
    def post(self, request, *args, **kwargs):
        if not self.link_form.is_valid():
            messages.error(self.request, _('We had difficulties processing your input.'))
            return self.get(request, *args, **kwargs)

        user = self.link_form.cleaned_data.get('email')

        if settings.HAS_REDIS:
            from django_redis import get_redis_connection
            rc = get_redis_connection("redis")
            if rc.exists('pretix_resend_{}'.format(user)):
                messages.error(request, _('We already sent you an email in the last 24 hours.'))
                return redirect(eventreverse(self.request.event, 'presale:event.resend_link'))
            else:
                rc.setex('pretix_resend_{}'.format(user), 3600 * 24, '1')

        orders = self.request.event.orders.filter(email__iexact=user)
        order_context = []

        for order in orders:
            url = build_absolute_uri(
                self.request.event,
                'presale:event.order',
                kwargs={'order': order.code, 'secret': order.secret}
            )
            order_context.append(' - {} - {}'.format(order, url))

        if not orders:
            user = INVALID_ADDRESS

        subject = _('Your orders for {}'.format(self.request.event))
        template = self.request.event.settings.mail_text_resend_all_links
        context = {
            'orders': '\n'.join(order_context),
            'event': self.request.event,
        }
        try:
            mail(user, subject, template, context, event=self.request.event, locale=self.request.LANGUAGE_CODE)
        except SendMailException:
            logger = logging.getLogger('pretix.presale.user')
            logger.exception('A mail resending order links to {} could not be sent.'.format(user))
            messages.error(self.request, _('We have trouble sending emails right now, please check back later.'))
            return self.get(request, *args, **kwargs)

        messages.success(self.request, _('If there were any orders by this user, they will receive an email with their order codes.'))
        return redirect(eventreverse(self.request.event, 'presale:event.index'))
Esempio n. 12
0
 def get_prev_url(self, request):
     prev = self.get_prev_applicable(request)
     if not prev:
         kwargs = {}
         if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
             kwargs['cart_namespace'] = request.resolver_match.kwargs['cart_namespace']
         return eventreverse(self.request.event, 'presale:event.index', kwargs=kwargs)
     else:
         return prev.get_step_url(request)
Esempio n. 13
0
    def get(self, request, *args, **kwargs):
        from pretix.presale.views.cart import get_or_create_cart_id

        self.subevent = None
        if request.GET.get('src', '') == 'widget' and 'take_cart_id' in request.GET:
            # User has clicked "Open in a new tab" link in widget
            get_or_create_cart_id(request)
            return redirect(eventreverse(request.event, 'presale:event.index', kwargs=kwargs))
        elif request.GET.get('iframe', '') == '1' and 'take_cart_id' in request.GET:
            # Widget just opened, a cart already exists. Let's to a stupid redirect to check if cookies are disabled
            get_or_create_cart_id(request)
            return redirect(eventreverse(request.event, 'presale:event.index', kwargs=kwargs) + '?require_cookie=true&cart_id={}'.format(
                request.GET.get('take_cart_id')
            ))
        elif request.GET.get('iframe', '') == '1' and len(self.request.GET.get('widget_data', '{}')) > 3:
            # We've been passed data from a widget, we need to create a cart session to store it.
            get_or_create_cart_id(request)
        elif 'require_cookie' in request.GET and settings.SESSION_COOKIE_NAME not in request.COOKIES:
            # Cookies are in fact not supported
            r = render(request, 'pretixpresale/event/cookies.html', {
                'url': eventreverse(
                    request.event, "presale:event.index", kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''}
                ) + (
                    "?src=widget&take_cart_id={}".format(request.GET.get('cart_id'))
                    if "cart_id" in request.GET else ""
                )
            })
            r._csp_ignore = True
            return r

        if request.event.has_subevents:
            if 'subevent' in kwargs:
                self.subevent = request.event.subevents.using(settings.DATABASE_REPLICA).filter(pk=kwargs['subevent'], active=True).first()
                if not self.subevent:
                    raise Http404()
                return super().get(request, *args, **kwargs)
            else:
                return super().get(request, *args, **kwargs)
        else:
            if 'subevent' in kwargs:
                return redirect(self.get_index_url())
            else:
                return super().get(request, *args, **kwargs)
Esempio n. 14
0
def success(request, *args, **kwargs):
    pid = request.GET.get('paymentId')
    token = request.GET.get('token')
    payer = request.GET.get('PayerID')
    request.session['payment_paypal_token'] = token
    request.session['payment_paypal_payer'] = payer

    urlkwargs = {}
    if 'cart_namespace' in kwargs:
        urlkwargs['cart_namespace'] = kwargs['cart_namespace']

    if request.session.get('payment_paypal_payment'):
        payment = OrderPayment.objects.get(pk=request.session.get('payment_paypal_payment'))
    else:
        payment = None

    if pid == request.session.get('payment_paypal_id', None):
        if payment:
            prov = Paypal(request.event)
            try:
                resp = prov.execute_payment(request, payment)
            except PaymentException as e:
                messages.error(request, str(e))
                urlkwargs['step'] = 'payment'
                return redirect(eventreverse(request.event, 'presale:event.checkout', kwargs=urlkwargs))
            if resp:
                return resp
    else:
        messages.error(request, _('Invalid response from PayPal received.'))
        logger.error('Session did not contain payment_paypal_id')
        urlkwargs['step'] = 'payment'
        return redirect(eventreverse(request.event, 'presale:event.checkout', kwargs=urlkwargs))

    if payment:
        return redirect(eventreverse(request.event, 'presale:event.order', kwargs={
            'order': payment.order.code,
            'secret': payment.order.secret
        }) + ('?paid=yes' if payment.order.status == Order.STATUS_PAID else ''))
    else:
        urlkwargs['step'] = 'confirm'
        return redirect(eventreverse(request.event, 'presale:event.checkout', kwargs=urlkwargs))
Esempio n. 15
0
def add_subevents_for_days(qs, before, after, ebd, timezones, event=None, cart_namespace=None):
    qs = qs.filter(active=True).filter(
        Q(Q(date_to__gte=before) & Q(date_from__lte=after)) |
        Q(Q(date_from__lte=after) & Q(date_to__gte=before)) |
        Q(Q(date_to__isnull=True) & Q(date_from__gte=before) & Q(date_from__lte=after))
    ).order_by(
        'date_from'
    )
    for se in qs:
        kwargs = {'subevent': se.pk}
        if cart_namespace:
            kwargs['cart_namespace'] = cart_namespace

        settings = event.settings if event else se.event.settings
        timezones.add(settings.timezones)
        tz = pytz.timezone(settings.timezone)
        datetime_from = se.date_from.astimezone(tz)
        date_from = datetime_from.date()
        if se.event.settings.show_date_to and se.date_to:
            date_to = se.date_to.astimezone(tz).date()
            d = max(date_from, before.date())
            while d <= date_to and d <= after.date():
                first = d == date_from
                ebd[d].append({
                    'continued': not first,
                    'timezone': settings.timezone,
                    'time': datetime_from.time().replace(tzinfo=None) if first and settings.show_times else None,
                    'event': se,
                    'url': eventreverse(se.event, 'presale:event.index', kwargs=kwargs)
                })
                d += timedelta(days=1)

        else:
            ebd[date_from].append({
                'event': se,
                'continued': False,
                'time': datetime_from.time().replace(tzinfo=None) if se.event.settings.show_times else None,
                'url': eventreverse(se.event, 'presale:event.index', kwargs=kwargs),
                'timezone': se.event.settings.timezone,
            })
Esempio n. 16
0
def add_events_for_days(request, baseqs, before, after, ebd, timezones):
    qs = baseqs.filter(is_public=True, live=True, has_subevents=False).filter(
        Q(Q(date_to__gte=before) & Q(date_from__lte=after)) |
        Q(Q(date_from__lte=after) & Q(date_to__gte=before)) |
        Q(Q(date_to__isnull=True) & Q(date_from__gte=before) & Q(date_from__lte=after))
    ).order_by(
        'date_from'
    ).prefetch_related(
        '_settings_objects', 'organizer___settings_objects'
    )
    if hasattr(request, 'organizer'):
        qs = filter_qs_by_attr(qs, request)
    for event in qs:
        timezones.add(event.settings.timezones)
        tz = pytz.timezone(event.settings.timezone)
        datetime_from = event.date_from.astimezone(tz)
        date_from = datetime_from.date()
        if event.settings.show_date_to and event.date_to:
            date_to = event.date_to.astimezone(tz).date()
            d = max(date_from, before.date())
            while d <= date_to and d <= after.date():
                first = d == date_from
                ebd[d].append({
                    'event': event,
                    'continued': not first,
                    'time': datetime_from.time().replace(tzinfo=None) if first and event.settings.show_times else None,
                    'url': eventreverse(event, 'presale:event.index'),
                    'timezone': event.settings.timezone,
                })
                d += timedelta(days=1)

        else:
            ebd[date_from].append({
                'event': event,
                'continued': False,
                'time': datetime_from.time().replace(tzinfo=None) if event.settings.show_times else None,
                'url': eventreverse(event, 'presale:event.index'),
                'timezone': event.settings.timezone,
            })
Esempio n. 17
0
def success(request, organizer=None, event=None):
    pid = request.GET.get('paymentId')
    token = request.GET.get('token')
    payer = request.GET.get('PayerID')
    if pid == request.session.get('payment_paypal_id', None):
        request.session['payment_paypal_token'] = token
        request.session['payment_paypal_payer'] = payer
        try:
            event = Event.objects.get(id=request.session['payment_paypal_event'])
            if request.session.get('payment_paypal_order'):
                prov = Paypal(event)
                order = Order.objects.get(pk=request.session.get('payment_paypal_order'))
                resp = prov.payment_perform(request, order)
                return redirect(resp or eventreverse(event, 'presale:event.order', kwargs={
                    'order': order.code,
                    'secret': order.secret
                }) + '?paid=yes')
            return redirect(eventreverse(event, 'presale:event.checkout', kwargs={'step': 'confirm'}))
        except Event.DoesNotExist:
            pass  # TODO: Handle this
    else:
        pass  # TODO: Handle this
Esempio n. 18
0
def success(request):
    pid = request.GET.get('paymentId')
    token = request.GET.get('token')
    payer = request.GET.get('PayerID')
    if pid == request.session['payment_paypal_id']:
        request.session['payment_paypal_token'] = token
        request.session['payment_paypal_payer'] = payer
        try:
            event = Event.objects.current.get(identity=request.session['payment_paypal_event'])
            return redirect(eventreverse(event, 'presale:event.checkout', kwargs={'step': 'confirm'}))
        except Event.DoesNotExist:
            pass  # TODO: Handle this
    else:
        pass  # TODO: Handle this
Esempio n. 19
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['voucher'] = self.voucher
        context['max_times'] = self.voucher.max_usages - self.voucher.redeemed

        # Fetch all items
        items, display_add_to_cart = get_grouped_items(self.request.event, self.subevent,
                                                       voucher=self.voucher, channel=self.request.sales_channel)

        # Calculate how many options the user still has. If there is only one option, we can
        # check the box right away ;)
        context['options'] = sum([(len(item.available_variations) if item.has_variations else 1)
                                  for item in items])

        # Regroup those by category
        context['items_by_category'] = item_group_by_category(items)

        context['subevent'] = self.subevent

        context['new_tab'] = (
            'require_cookie' in self.request.GET and
            settings.SESSION_COOKIE_NAME not in self.request.COOKIES
            # Cookies are not supported! Lets just make the form open in a new tab
        )

        if self.request.event.settings.redirect_to_checkout_directly:
            context['cart_redirect'] = eventreverse(self.request.event, 'presale:event.checkout.start',
                                                    kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''})
        else:
            context['cart_redirect'] = eventreverse(self.request.event, 'presale:event.index',
                                                    kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''})
        if context['cart_redirect'].startswith('https:'):
            context['cart_redirect'] = '/' + context['cart_redirect'].split('/', 3)[3]

        return context
Esempio n. 20
0
    def get(self, request, *args, **kwargs):
        if request.GET.get('iframe', '') == '1' and 'require_cookie' not in request.GET:
            # Widget just opened. Let's to a stupid redirect to check if cookies are disabled
            return redirect(request.get_full_path() + '&require_cookie=true')
        elif 'require_cookie' in request.GET and settings.SESSION_COOKIE_NAME not in request.COOKIES:
            # Cookies are in fact not supported. We can't even display the form, since we can't get CSRF right without
            # cookies.
            r = render(request, 'pretixpresale/event/cookies.html', {
                'url': eventreverse(
                    request.event, "presale:event.waitinglist", kwargs={'cart_namespace': kwargs.get('cart_namespace')}
                ) + '?' + url_replace(request, 'require_cookie', '', 'iframe', '')
            })
            r._csp_ignore = True
            return r

        return super().get(request, *args, **kwargs)
Esempio n. 21
0
    def get(self, request, *args, **kwargs):
        prov = self.pprov
        prov._init_api()
        src = stripe.Source.retrieve(request.GET.get('source'), **prov.api_kwargs)
        if src.client_secret != request.GET.get('client_secret'):
            messages.error(self.request, _('Sorry, there was an error in the payment process. Please check the link '
                                           'in your emails to continue.'))
            return redirect(eventreverse(self.request.event, 'presale:event.index'))

        with transaction.atomic():
            self.order.refresh_from_db()
            self.payment.refresh_from_db()
            if self.payment.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
                if 'payment_stripe_token' in request.session:
                    del request.session['payment_stripe_token']
                return self._redirect_to_order()

            if src.status == 'chargeable':
                try:
                    prov._charge_source(request, src.id, self.payment)
                except PaymentException as e:
                    messages.error(request, str(e))
                    return self._redirect_to_order()
                finally:
                    if 'payment_stripe_token' in request.session:
                        del request.session['payment_stripe_token']
            elif src.status == 'consumed':
                # Webhook was faster, wow! ;)
                if 'payment_stripe_token' in request.session:
                    del request.session['payment_stripe_token']
                return self._redirect_to_order()
            elif src.status == 'pending':
                self.payment.state = OrderPayment.PAYMENT_STATE_PENDING
                self.payment.info = str(src)
                self.payment.save()
            else:  # failed or canceled
                self.payment.state = OrderPayment.PAYMENT_STATE_FAILED
                self.payment.info = str(src)
                self.payment.save()
                self.payment.order.log_action('pretix.event.order.payment.failed', {
                    'local_id': self.payment.local_id,
                    'provider': self.payment.provider,
                    'info': str(src)
                })
                messages.error(self.request, _('We had trouble authorizing your card payment. Please try again and '
                                               'get in touch with us if this problem persists.'))
        return self._redirect_to_order()
Esempio n. 22
0
 def get_next_url(self):
     if "next" in self.request.GET and is_safe_url(self.request.GET.get("next"), allowed_hosts=None):
         u = self.request.GET.get('next')
     else:
         kwargs = {}
         if 'cart_namespace' in self.kwargs:
             kwargs['cart_namespace'] = self.kwargs['cart_namespace']
         u = eventreverse(self.request.event, 'presale:event.index', kwargs=kwargs)
     if '?' in u:
         u += '&require_cookie=true'
     else:
         u += '?require_cookie=true'
     disclose_cart_id = (
         'iframe' in self.request.GET or settings.SESSION_COOKIE_NAME not in self.request.COOKIES
     ) and self.kwargs.get('cart_namespace')
     if disclose_cart_id:
         cart_id = get_or_create_cart_id(self.request)
         u += '&cart_id={}'.format(cart_id)
     return u
Esempio n. 23
0
    def post(self, request, *args, **kwargs):
        s = SessionStore(request.POST.get('session'))

        try:
            data = s.load()
        except:
            raise PermissionDenied(_('Please go back and try again.'))

        parent = data.get('pretix_event_access_{}'.format(request.event.pk))

        sparent = SessionStore(parent)
        try:
            parentdata = sparent.load()
        except:
            raise PermissionDenied(_('Please go back and try again.'))
        else:
            if 'event_access' not in parentdata:
                raise PermissionDenied(_('Please go back and try again.'))

        request.session['pretix_event_access_{}'.format(request.event.pk)] = parent
        return redirect(eventreverse(request.event, 'presale:event.index'))
Esempio n. 24
0
 def get_next_url(self):
     if "next" in self.request.GET and is_safe_url(
             self.request.GET.get("next"), allowed_hosts=None):
         u = self.request.GET.get('next')
     else:
         kwargs = {}
         if 'cart_namespace' in self.kwargs:
             kwargs['cart_namespace'] = self.kwargs['cart_namespace']
         u = eventreverse(self.request.event,
                          'presale:event.index',
                          kwargs=kwargs)
     if '?' in u:
         u += '&require_cookie=true'
     else:
         u += '?require_cookie=true'
     disclose_cart_id = (
         'iframe' in self.request.GET or settings.SESSION_COOKIE_NAME
         not in self.request.COOKIES) and self.kwargs.get('cart_namespace')
     if disclose_cart_id:
         cart_id = get_or_create_cart_id(self.request)
         u += '&cart_id={}'.format(cart_id)
     return u
Esempio n. 25
0
    def post(self, request, *args, **kwargs):
        s = SessionStore(request.POST.get('session'))

        try:
            data = s.load()
        except:
            raise PermissionDenied(_('Please go back and try again.'))

        parent = data.get('pretix_event_access_{}'.format(request.event.pk))

        sparent = SessionStore(parent)
        try:
            parentdata = sparent.load()
        except:
            raise PermissionDenied(_('Please go back and try again.'))
        else:
            if 'event_access' not in parentdata:
                raise PermissionDenied(_('Please go back and try again.'))

        request.session['pretix_event_access_{}'.format(
            request.event.pk)] = parent
        return redirect(eventreverse(request.event, 'presale:event.index'))
Esempio n. 26
0
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        if not self.positions and "async_id" not in request.GET:
            messages.error(request, _("Your cart is empty"))
            return redirect(eventreverse(self.request.event, 'presale:event.index'))

        flow = get_checkout_flow(self.request.event)
        for step in flow:
            if not step.is_applicable(request):
                continue
            if 'step' not in kwargs:
                return redirect(step.get_step_url())
            is_selected = (step.identifier == kwargs.get('step', ''))
            if "async_id" not in request.GET and not is_selected and not step.is_completed(request, warn=not is_selected):
                return redirect(step.get_step_url())
            if is_selected:
                if request.method.lower() in self.http_method_names:
                    handler = getattr(step, request.method.lower(), self.http_method_not_allowed)
                else:
                    handler = self.http_method_not_allowed
                return handler(request)
        raise Http404()
Esempio n. 27
0
def confirm_messages(sender, *args, **kwargs):
    cached = sender.cache.get('pages_confirm_messages_' + get_language())
    if cached is None:
        pages = list(
            Page.objects.filter(event=sender, require_confirmation=True))
        if pages:
            cached = {
                'pages':
                _('I have read and agree with the content of the following pages: {plist}'
                  ).format(plist=', '.join([
                      '<a href="{url}" target="_blank">{title}</a>'.format(
                          title=str(p.title),
                          url=eventreverse(sender,
                                           'plugins:pretix_pages:show',
                                           kwargs={'slug': p.slug}))
                      for p in pages
                  ]))
            }
        else:
            cached = {}
        sender.cache.set('pages_confirm_messages_' + get_language(), cached)
    return cached
Esempio n. 28
0
    def get(self, request, *args, **kwargs):
        prov = self.pprov
        prov._init_api()
        src = stripe.Source.retrieve(request.GET.get('source'),
                                     **prov.api_kwargs)
        if src.client_secret != request.GET.get('client_secret'):
            messages.error(
                self.request,
                _('Sorry, there was an error in the payment process. Please check the link '
                  'in your emails to continue.'))
            return redirect(
                eventreverse(self.request.event, 'presale:event.index'))

        with transaction.atomic():
            self.order.refresh_from_db()
            self.payment.refresh_from_db()
            if self.payment.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
                if 'payment_stripe_token' in request.session:
                    del request.session['payment_stripe_token']
                return self._redirect_to_order()

            if src.status == 'chargeable':
                try:
                    prov._charge_source(request, src.id, self.payment)
                except PaymentException as e:
                    messages.error(request, str(e))
                    return self._redirect_to_order()
                finally:
                    if 'payment_stripe_token' in request.session:
                        del request.session['payment_stripe_token']
            else:
                self.payment.state = OrderPayment.PAYMENT_STATE_FAILED
                self.payment.info = str(src)
                self.payment.save()
                messages.error(
                    self.request,
                    _('We had trouble authorizing your card payment. Please try again and '
                      'get in touch with us if this problem persists.'))
        return self._redirect_to_order()
Esempio n. 29
0
    def get_next_page(self):
        if getattr(self.request, 'event_domain', False):
            next_page = '/'
        else:
            next_page = eventreverse(self.request.organizer,
                                     'presale:organizer.index',
                                     kwargs={})

        if (self.redirect_field_name in self.request.POST
                or self.redirect_field_name in self.request.GET):
            next_page = self.request.POST.get(
                self.redirect_field_name,
                self.request.GET.get(self.redirect_field_name))
            url_is_safe = url_has_allowed_host_and_scheme(
                url=next_page,
                allowed_hosts=None,
                require_https=self.request.is_secure(),
            )
            # Security check -- Ensure the user-originating redirection URL is
            # safe.
            if not url_is_safe:
                next_page = self.request.path
        return next_page
Esempio n. 30
0
    def get(self, request, *args, **kwargs):
        if request.GET.get('iframe',
                           '') == '1' and 'require_cookie' not in request.GET:
            # Widget just opened. Let's to a stupid redirect to check if cookies are disabled
            return redirect(request.get_full_path() + '&require_cookie=true')
        elif 'require_cookie' in request.GET and settings.SESSION_COOKIE_NAME not in request.COOKIES:
            # Cookies are in fact not supported. We can't even display the form, since we can't get CSRF right without
            # cookies.
            r = render(
                request, 'pretixpresale/event/cookies.html', {
                    'url':
                    eventreverse(request.event,
                                 "presale:event.waitinglist",
                                 kwargs={
                                     'cart_namespace':
                                     kwargs.get('cart_namespace')
                                 }) + '?' +
                    url_replace(request, 'require_cookie', '', 'iframe', '')
                })
            r._csp_ignore = True
            return r

        return super().get(request, *args, **kwargs)
Esempio n. 31
0
    def get_success_url(self):
        url = self.get_redirect_url()

        if not url:
            return eventreverse(self.request.organizer,
                                'presale:organizer.customer.profile',
                                kwargs={})

        if self.request.GET.get(
                "request_cross_domain_customer_auth") == "true":
            otpstore = SessionStore()
            otpstore[
                f'customer_cross_domain_auth_{self.request.organizer.pk}'] = self.request.session.session_key
            otpstore.set_expiry(60)
            otpstore.save(must_create=True)
            otp = otpstore.session_key

            u = urlparse(url)
            qsl = parse_qs(u.query)
            qsl['cross_domain_customer_auth'] = otp
            url = urlunparse((u.scheme, u.netloc, u.path, u.params,
                              urlencode(qsl, doseq=True), u.fragment))

        return url
Esempio n. 32
0
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        has_cart = CartPosition.objects.filter(
            cart_id=self.request.session.session_key, event=self.request.event).exists()
        if not has_cart and "async_id" not in request.GET:
            messages.error(request, _("Your cart is empty"))
            return redirect(eventreverse(self.request.event, 'presale:event.index'))

        flow = get_checkout_flow(self.request.event)
        for step in flow:
            if not step.is_applicable(request):
                continue
            if 'step' not in kwargs:
                return redirect(step.get_step_url())
            is_selected = (step.identifier == kwargs.get('step', ''))
            if "async_id" not in request.GET and not is_selected and not step.is_completed(request, warn=not is_selected):
                return redirect(step.get_step_url())
            if is_selected:
                if request.method.lower() in self.http_method_names:
                    handler = getattr(step, request.method.lower(), self.http_method_not_allowed)
                else:
                    handler = self.http_method_not_allowed
                return handler(request)
        raise Http404()
Esempio n. 33
0
 def get_self_url(self):
     return eventreverse(self.request.event,
                         'presale:event.order.download' if 'position' in self.kwargs
                         else 'presale:event.order.download.combined',
                         kwargs=self.kwargs)
Esempio n. 34
0
 def get_next_url(self):
     if "next" in self.request.GET and '://' not in self.request.GET.get(
             'next'):
         return self.request.GET.get('next')
     else:
         return eventreverse(self.request.event, 'presale:event.index')
Esempio n. 35
0
 def get_self_url(self):
     return eventreverse(self.request.event,
                         'presale:event.order.position.download',
                         kwargs=self.kwargs)
Esempio n. 36
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Show voucher option if an event is selected and vouchers exist
        vouchers_exist = self.request.event.cache.get('vouchers_exist')
        if vouchers_exist is None:
            vouchers_exist = self.request.event.vouchers.exists()
            self.request.event.cache.set('vouchers_exist', vouchers_exist)

        if not self.request.event.has_subevents or self.subevent:
            # Fetch all items
            items, display_add_to_cart = get_grouped_items(
                self.request.event,
                self.subevent,
                filter_items=self.request.GET.getlist('item'),
                filter_categories=self.request.GET.getlist('category'),
                channel=self.request.sales_channel.identifier)
            context['itemnum'] = len(items)
            context['allfree'] = all(
                item.display_price.gross == Decimal('0.00')
                for item in items if not item.has_variations) and all(
                    all(var.display_price.gross == Decimal('0.00')
                        for var in item.available_variations)
                    for item in items if item.has_variations)

            # Regroup those by category
            context['items_by_category'] = item_group_by_category(items)
            context['display_add_to_cart'] = display_add_to_cart

            context['show_vouchers'] = vouchers_exist
            context['vouchers_exist'] = vouchers_exist
        else:
            context['show_vouchers'] = False
            context['vouchers_exist'] = vouchers_exist

        context['ev'] = self.subevent or self.request.event
        context['subevent'] = self.subevent
        context['cart'] = self.get_cart()
        context['has_addon_choices'] = get_cart(
            self.request).filter(item__addons__isnull=False).exists()

        if self.subevent:
            context['frontpage_text'] = str(self.subevent.frontpage_text)
        else:
            context['frontpage_text'] = str(
                self.request.event.settings.frontpage_text)

        context['list_type'] = self.request.GET.get(
            "style", self.request.event.settings.event_list_type)
        if context['list_type'] not in (
                "calendar",
                "week") and self.request.event.subevents.count() > 100:
            if self.request.event.settings.event_list_type not in ("calendar",
                                                                   "week"):
                self.request.event.settings.event_list_type = "calendar"
            context['list_type'] = "calendar"

        if context[
                'list_type'] == "calendar" and self.request.event.has_subevents:
            self._set_month_year()
            tz = pytz.timezone(self.request.event.settings.timezone)
            _, ndays = calendar.monthrange(self.year, self.month)
            before = datetime(self.year, self.month, 1, 0, 0, 0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(self.year, self.month, ndays, 0, 0, 0,
                             tzinfo=tz) + timedelta(days=1)

            context['date'] = date(self.year, self.month, 1)
            context['before'] = before
            context['after'] = after

            ebd = defaultdict(list)
            add_subevents_for_days(
                filter_qs_by_attr(
                    self.request.event.subevents_annotated(
                        self.request.sales_channel.identifier).using(
                            settings.DATABASE_REPLICA), self.request), before,
                after, ebd, set(), self.request.event,
                kwargs.get('cart_namespace'))

            context['show_names'] = ebd.get(
                '_subevents_different_names', False) or sum(
                    len(i) for i in ebd.values() if isinstance(i, list)) < 2
            context['weeks'] = weeks_for_template(ebd, self.year, self.month)
            context['months'] = [date(self.year, i + 1, 1) for i in range(12)]
            context['years'] = range(now().year - 2, now().year + 3)
        elif context[
                'list_type'] == "week" and self.request.event.has_subevents:
            self._set_week_year()
            tz = pytz.timezone(self.request.event.settings.timezone)
            week = isoweek.Week(self.year, self.week)
            before = datetime(week.monday().year,
                              week.monday().month,
                              week.monday().day,
                              0,
                              0,
                              0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(week.sunday().year,
                             week.sunday().month,
                             week.sunday().day,
                             0,
                             0,
                             0,
                             tzinfo=tz) + timedelta(days=1)

            context['date'] = week.monday()
            context['before'] = before
            context['after'] = after

            ebd = defaultdict(list)
            add_subevents_for_days(
                filter_qs_by_attr(
                    self.request.event.subevents_annotated(
                        self.request.sales_channel.identifier).using(
                            settings.DATABASE_REPLICA), self.request), before,
                after, ebd, set(), self.request.event,
                kwargs.get('cart_namespace'))

            context['show_names'] = ebd.get(
                '_subevents_different_names', False) or sum(
                    len(i) for i in ebd.values() if isinstance(i, list)) < 2
            context['days'] = days_for_template(ebd, week)
            context['weeks'] = [date(self.year, i + 1, 1) for i in range(12)]
            context['weeks'] = [i + 1 for i in range(53)]
            context['years'] = range(now().year - 2, now().year + 3)
            context['week_format'] = get_format('WEEK_FORMAT')
            if context['week_format'] == 'WEEK_FORMAT':
                context['week_format'] = WEEK_FORMAT
        elif self.request.event.has_subevents:
            context['subevent_list'] = self.request.event.subevents_sorted(
                filter_qs_by_attr(
                    self.request.event.subevents_annotated(
                        self.request.sales_channel.identifier).using(
                            settings.DATABASE_REPLICA), self.request))

        context['show_cart'] = (context['cart']['positions']
                                and (self.request.event.has_subevents
                                     or self.request.event.presale_is_running))
        if self.request.event.settings.redirect_to_checkout_directly:
            context['cart_redirect'] = eventreverse(
                self.request.event,
                'presale:event.checkout.start',
                kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''})
            if context['cart_redirect'].startswith('https:'):
                context[
                    'cart_redirect'] = '/' + context['cart_redirect'].split(
                        '/', 3)[3]
        else:
            context['cart_redirect'] = self.request.path

        return context
Esempio n. 37
0
 def get_success_url(self):
     return eventreverse(self.request.organizer, 'presale:organizer.customer.profile', kwargs={})
Esempio n. 38
0
def test_event_custom_domain_front_page(env):
    KnownDomain.objects.create(domainname='foobar', organizer=env[0])
    assert eventreverse(env[1], 'presale:event.index') == 'http://foobar/2015/'
    assert eventreverse(env[0], 'presale:organizer.index') == 'http://foobar/'
Esempio n. 39
0
def test_event_main_domain_kwargs(env):
    assert eventreverse(env[1], 'presale:event.checkout',
                        {'step': 'payment'}) == '/mrmcd/2015/checkout/payment/'
Esempio n. 40
0
def test_event_custom_domain_kwargs(env):
    KnownDomain.objects.create(domainname='foobar', organizer=env[0])
    assert eventreverse(
        env[1], 'presale:event.checkout',
        {'step': 'payment'}) == 'http://foobar/2015/checkout/payment/'
Esempio n. 41
0
def test_event_main_domain_front_page(env):
    assert eventreverse(env[1], 'presale:event.index') == '/mrmcd/2015/'
    assert eventreverse(env[0], 'presale:organizer.index') == '/mrmcd/'
Esempio n. 42
0
 def get(self, request, *args, **kwargs):
     hashes = request.session.get('pretix_unlock_hashes', [])
     hashes.append(kwargs.get('hash'))
     request.session['pretix_unlock_hashes'] = hashes
     return redirect(eventreverse(self.request.event,
                                  'presale:event.index'))
Esempio n. 43
0
 def get_prev_url(self, request):
     prev = self.get_prev_applicable(request)
     if not prev:
         return eventreverse(self.event, 'presale:event.index')
     else:
         return prev.get_step_url()
Esempio n. 44
0
 def get_order_url(self):
     return eventreverse(
         self.request.event, "presale:event.order", kwargs={"order": self.order.code, "secret": self.order.secret}
     )
Esempio n. 45
0
 def get_index_url(self):
     kwargs = {}
     if 'cart_namespace' in self.kwargs:
         kwargs['cart_namespace'] = self.kwargs['cart_namespace']
     return eventreverse(self.request.event, 'presale:event.index', kwargs=kwargs)
Esempio n. 46
0
def test_event_custom_domain_keep_scheme(env):
    settings.SITE_URL = 'https://example.com'
    KnownDomain.objects.create(domainname='foobar', organizer=env[0])
    assert eventreverse(env[1],
                        'presale:event.index') == 'https://foobar/2015/'
Esempio n. 47
0
 def get_success_url(self):
     url = self.get_redirect_url()
     return url or eventreverse(self.request.organizer, 'presale:organizer.customer.login', kwargs={})
Esempio n. 48
0
def test_event_main_domain_cache(env):
    env[0].get_cache().clear()
    with assert_num_queries(1):
        eventreverse(env[1], 'presale:event.index')
    with assert_num_queries(0):
        eventreverse(env[1], 'presale:event.index')
Esempio n. 49
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if not self.request.event.has_subevents or self.subevent:
            # Fetch all items
            items, display_add_to_cart = get_grouped_items(
                self.request.event,
                self.subevent,
                channel=self.request.sales_channel.identifier)
            context['itemnum'] = len(items)

            # Regroup those by category
            context['items_by_category'] = item_group_by_category(items)
            context['display_add_to_cart'] = display_add_to_cart

            # Show voucher option if an event is selected and vouchers exist
            vouchers_exist = self.request.event.cache.get('vouchers_exist')
            if vouchers_exist is None:
                vouchers_exist = self.request.event.vouchers.exists()
                self.request.event.cache.set('vouchers_exist', vouchers_exist)
            context['show_vouchers'] = vouchers_exist
        else:
            context['show_vouchers'] = False

        context['ev'] = self.subevent or self.request.event
        context['subevent'] = self.subevent
        context['cart'] = self.get_cart()
        context['has_addon_choices'] = get_cart(
            self.request).filter(item__addons__isnull=False).exists()

        if self.subevent:
            context['frontpage_text'] = str(self.subevent.frontpage_text)
        else:
            context['frontpage_text'] = str(
                self.request.event.settings.frontpage_text)

        context['list_type'] = self.request.GET.get(
            "style", self.request.event.settings.event_list_type)

        if context['list_type'] == "calendar":
            self._set_month_year()
            tz = pytz.timezone(self.request.event.settings.timezone)
            _, ndays = calendar.monthrange(self.year, self.month)
            before = datetime(self.year, self.month, 1, 0, 0, 0,
                              tzinfo=tz) - timedelta(days=1)
            after = datetime(self.year, self.month, ndays, 0, 0, 0,
                             tzinfo=tz) + timedelta(days=1)

            context['date'] = date(self.year, self.month, 1)
            context['before'] = before
            context['after'] = after

            ebd = defaultdict(list)
            add_subevents_for_days(
                filter_qs_by_attr(
                    self.request.event.subevents_annotated(
                        self.request.sales_channel.identifier).using(
                            settings.DATABASE_REPLICA), self.request), before,
                after, ebd, set(), self.request.event,
                kwargs.get('cart_namespace'))

            context['weeks'] = weeks_for_template(ebd, self.year, self.month)
            context['months'] = [date(self.year, i + 1, 1) for i in range(12)]
            context['years'] = range(now().year - 2, now().year + 3)
        else:
            context['subevent_list'] = self.request.event.subevents_sorted(
                filter_qs_by_attr(
                    self.request.event.subevents_annotated(
                        self.request.sales_channel.identifier).using(
                            settings.DATABASE_REPLICA), self.request))

        context['show_cart'] = (context['cart']['positions']
                                and (self.request.event.has_subevents
                                     or self.request.event.presale_is_running))
        context['show_dates'] = (self.request.event.has_subevents
                                 and ('cart_namespace' not in self.kwargs
                                      or not self.subevent))
        if self.request.event.settings.redirect_to_checkout_directly:
            context['cart_redirect'] = eventreverse(
                self.request.event,
                'presale:event.checkout.start',
                kwargs={'cart_namespace': kwargs.get('cart_namespace') or ''})
            if context['cart_redirect'].startswith('https:'):
                context[
                    'cart_redirect'] = '/' + context['cart_redirect'].split(
                        '/', 3)[3]
        else:
            context['cart_redirect'] = self.request.path

        return context
Esempio n. 50
0
def add_subevents_for_days(qs, before, after, ebd, timezones, event=None, cart_namespace=None, voucher=None):
    qs = qs.filter(active=True, is_public=True).filter(
        Q(Q(date_to__gte=before) & Q(date_from__lte=after)) |
        Q(Q(date_from__lte=after) & Q(date_to__gte=before)) |
        Q(Q(date_to__isnull=True) & Q(date_from__gte=before) & Q(date_from__lte=after))
    ).order_by(
        'date_from'
    )

    quotas_to_compute = []
    for se in qs:
        if se.presale_is_running:
            quotas_to_compute += se.active_quotas

    name = None
    qcache = {}
    if quotas_to_compute:
        qa = QuotaAvailability()
        qa.queue(*quotas_to_compute)
        qa.compute(allow_cache=True)
        qcache.update(qa.results)

    for se in qs:
        if qcache:
            se._quota_cache = qcache
        kwargs = {'subevent': se.pk}
        if cart_namespace:
            kwargs['cart_namespace'] = cart_namespace

        s = event.settings if event else se.event.settings

        if s.event_list_available_only:
            hide = se.presale_has_ended or (
                (not voucher or not voucher.allow_ignore_quota) and
                se.best_availability_state is not None and
                se.best_availability_state < Quota.AVAILABILITY_RESERVED
            )
            if hide:
                continue

        timezones.add(s.timezones)
        tz = pytz.timezone(s.timezone)
        datetime_from = se.date_from.astimezone(tz)
        date_from = datetime_from.date()
        if name is None:
            name = str(se.name)
        elif str(se.name) != name:
            ebd['_subevents_different_names'] = True
        if s.show_date_to and se.date_to:
            datetime_to = se.date_to.astimezone(tz)
            date_to = se.date_to.astimezone(tz).date()
            d = max(date_from, before.date())
            while d <= date_to and d <= after.date():
                first = d == date_from
                ebd[d].append({
                    'continued': not first,
                    'timezone': s.timezone,
                    'time': datetime_from.time().replace(tzinfo=None) if first and s.show_times else None,
                    'time_end': (
                        datetime_to.time().replace(tzinfo=None)
                        if (date_to == date_from or (
                            date_to == date_from + timedelta(days=1) and datetime_to.time() < datetime_from.time()
                        )) and s.show_times
                        else None
                    ),
                    'event': se,
                    'url': (
                        eventreverse(se.event, 'presale:event.redeem',
                                     kwargs={k: v for k, v in kwargs.items() if k != 'subevent'}) + f'?subevent={se.pk}&voucher={quote(voucher.code)}'
                        if voucher
                        else eventreverse(se.event, 'presale:event.index', kwargs=kwargs)
                    )
                })
                d += timedelta(days=1)

        else:
            ebd[date_from].append({
                'event': se,
                'continued': False,
                'time': datetime_from.time().replace(tzinfo=None) if s.show_times else None,
                'url': (
                    eventreverse(se.event, 'presale:event.redeem',
                                 kwargs={k: v for k, v in kwargs.items() if k != 'subevent'}) + f'?subevent={se.pk}&voucher={quote(voucher.code)}'
                    if voucher
                    else eventreverse(se.event, 'presale:event.index', kwargs=kwargs)
                ),
                'timezone': s.timezone,
            })
Esempio n. 51
0
    def checkout_prepare(self, request: HttpRequest,
                         cart: Dict[str, Any]) -> Union[bool, str, None]:
        for p in get_cart(request):
            if p.item.issue_giftcard:
                messages.error(
                    request,
                    _("You cannot pay with gift cards when buying a gift card."
                      ))
                return

        cs = cart_session(request)
        try:
            gc = self.event.organizer.accepted_gift_cards.get(
                secret=request.POST.get("giftcard"))
            if gc.currency != self.event.currency:
                messages.error(
                    request,
                    _("This gift card does not support this currency."))
                return
            if gc.testmode and not self.event.testmode:
                messages.error(
                    request,
                    _("This gift card can only be used in test mode."))
                return
            if not gc.testmode and self.event.testmode:
                messages.error(
                    request,
                    _("Only test gift cards can be used in test mode."))
                return
            if gc.value <= Decimal("0.00"):
                messages.error(
                    request, _("All credit on this gift card has been used."))
                return
            if 'gift_cards' not in cs:
                cs['gift_cards'] = []
            elif gc.pk in cs['gift_cards']:
                messages.error(
                    request,
                    _("This gift card is already used for your payment."))
                return
            cs['gift_cards'] = cs['gift_cards'] + [gc.pk]

            remainder = cart['total'] - gc.value
            if remainder >= Decimal('0.00'):
                del cs['payment']
                messages.success(
                    request,
                    _("Your gift card has been applied, but {} still need to be paid. Please select a payment method."
                      ).format(money_filter(remainder, self.event.currency)))
            else:
                messages.success(request,
                                 _("Your gift card has been applied."))

            kwargs = {'step': 'payment'}
            if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
                kwargs['cart_namespace'] = request.resolver_match.kwargs[
                    'cart_namespace']
            return eventreverse(self.event,
                                'presale:event.checkout',
                                kwargs=kwargs)
        except GiftCard.DoesNotExist:
            if self.event.vouchers.filter(
                    code__iexact=request.POST.get("giftcard")).exists():
                messages.warning(
                    request,
                    _("You entered a voucher instead of a gift card. Vouchers can only be entered on the first page of the shop below "
                      "the product selection."))
            else:
                messages.error(request, _("This gift card is not known."))
        except GiftCard.MultipleObjectsReturned:
            messages.error(
                request,
                _("This gift card can not be redeemed since its code is not unique. Please contact the organizer of this event."
                  ))
Esempio n. 52
0
 def get_next_url(self):
     if "next" in self.request.GET and "://" not in self.request.GET.get("next"):
         return self.request.GET.get("next")
     else:
         return eventreverse(self.request.event, "presale:event.index")
Esempio n. 53
0
    def get(self, request, *args, **kwargs):
        prov = self.pprov
        prov._init_api()
        try:
            src = stripe.Source.retrieve(request.GET.get('source'),
                                         **prov.api_kwargs)
        except stripe.error.InvalidRequestError:
            logger.exception('Could not retrieve source')
            messages.error(
                self.request,
                _('Sorry, there was an error in the payment process. Please check the link '
                  'in your emails to continue.'))
            return redirect(
                eventreverse(self.request.event, 'presale:event.index'))

        if src.client_secret != request.GET.get('client_secret'):
            messages.error(
                self.request,
                _('Sorry, there was an error in the payment process. Please check the link '
                  'in your emails to continue.'))
            return redirect(
                eventreverse(self.request.event, 'presale:event.index'))

        with transaction.atomic():
            self.order.refresh_from_db()
            self.payment.refresh_from_db()
            if self.payment.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
                if 'payment_stripe_token' in request.session:
                    del request.session['payment_stripe_token']
                return self._redirect_to_order()

            if src.status == 'chargeable':
                try:
                    prov._charge_source(request, src.id, self.payment)
                except PaymentException as e:
                    messages.error(request, str(e))
                    return self._redirect_to_order()
                finally:
                    if 'payment_stripe_token' in request.session:
                        del request.session['payment_stripe_token']
            elif src.status == 'consumed':
                # Webhook was faster, wow! ;)
                if 'payment_stripe_token' in request.session:
                    del request.session['payment_stripe_token']
                return self._redirect_to_order()
            elif src.status == 'pending':
                self.payment.state = OrderPayment.PAYMENT_STATE_PENDING
                self.payment.info = str(src)
                self.payment.save()
            else:  # failed or canceled
                self.payment.state = OrderPayment.PAYMENT_STATE_FAILED
                self.payment.info = str(src)
                self.payment.save()
                self.payment.order.log_action(
                    'pretix.event.order.payment.failed', {
                        'local_id': self.payment.local_id,
                        'provider': self.payment.provider,
                        'info': str(src)
                    })
                messages.error(
                    self.request,
                    _('We had trouble authorizing your card payment. Please try again and '
                      'get in touch with us if this problem persists.'))
        return self._redirect_to_order()
Esempio n. 54
0
def abort(request, *args, **kwargs):
    messages.error(request, _('It looks like you canceled the PayPal payment'))
    return redirect(
        eventreverse(request.event,
                     'presale:event.checkout',
                     kwargs={'step': 'payment'}))
Esempio n. 55
0
 def get_order_url(self):
     return eventreverse(self.request.event, 'presale:event.order', kwargs={
         'order': self.order.code,
         'secret': self.order.secret
     })
Esempio n. 56
0
 def get_index_url(self):
     kwargs = {}
     if 'cart_namespace' in self.kwargs:
         kwargs['cart_namespace'] = self.kwargs['cart_namespace']
     return eventreverse(self.request.event, 'presale:event.index', kwargs=kwargs)
Esempio n. 57
0
File: cart.py Progetto: rixx/pretix
 def get_next_url(self):
     if "next" in self.request.GET and '://' not in self.request.GET.get('next'):
         return self.request.GET.get('next')
     else:
         return eventreverse(self.request.event, 'presale:event.index')
Esempio n. 58
0
 def get_confirm_url(self):
     return eventreverse(
         self.request.event,
         "presale:event.order.pay.confirm",
         kwargs={"order": self.order.code, "secret": self.order.secret},
     )
Esempio n. 59
0
 def get_step_url(self):
     return eventreverse(self.event,
                         'presale:event.checkout',
                         kwargs={'step': self.identifier})
Esempio n. 60
0
 def get_step_url(self, request):
     kwargs = {'step': self.identifier}
     if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
         kwargs['cart_namespace'] = request.resolver_match.kwargs['cart_namespace']
     return eventreverse(self.event, 'presale:event.checkout', kwargs=kwargs)