mirror of
https://github.com/pretix/pretix.git
synced 2026-10-28 23:39:52 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85a141bb82 | ||
|
|
8f37338b91 | ||
|
|
ac01a08f68 | ||
|
|
ecda203362 | ||
|
|
77e2342a3b | ||
|
|
3689ad7bb5 | ||
|
|
b474664fb8 | ||
|
|
22a38f38dd | ||
|
|
838a0c4c78 | ||
|
|
b006de6d9c | ||
|
|
ebe152afe2 | ||
|
|
0aa2c1fdcf | ||
|
|
181f47de2f | ||
|
|
28de52a1ca | ||
|
|
af4c49f95b | ||
|
|
9663e46de9 | ||
|
|
7037b5ebf2 |
No files matched your search
@@ -19,4 +19,4 @@
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
__version__ = "2026.7.0"
|
||||
__version__ = "2026.7.3"
|
||||
@@ -0,0 +1,31 @@
|
||||
#
|
||||
# This file is part of pretix (Community Edition).
|
||||
#
|
||||
# Copyright (C) 2014-2020 Raphael Michel and contributors
|
||||
# Copyright (C) 2020-today pretix GmbH and contributors
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
|
||||
# Public License as published by the Free Software Foundation in version 3 of the License.
|
||||
#
|
||||
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
|
||||
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
|
||||
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
|
||||
# this file, see <https://pretix.eu/about/en/license>.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
def get_session_key_for_api_auth(user, auth, prefix='api-upload'):
|
||||
if user.is_authenticated:
|
||||
return f'{prefix}-User-{user.pk}'
|
||||
else:
|
||||
return f'{prefix}-{str(type(auth))}-{auth.pk}'
|
||||
|
||||
|
||||
def get_session_key_for_api_request(request, prefix='api-upload'):
|
||||
return get_session_key_for_api_auth(request.user, request.auth, prefix)
|
||||
@@ -101,6 +101,10 @@ class OAuthAccessToken(AbstractAccessToken):
|
||||
self.expires = now() - timedelta(hours=1)
|
||||
self.save(update_fields=['expires'])
|
||||
|
||||
def is_valid(self, scopes=None):
|
||||
# Can maybe be removed after upgrading django-oauth-toolkit to 3.4.1
|
||||
return super().is_valid(scopes) and self.application.is_usable(None)
|
||||
|
||||
|
||||
class OAuthRefreshToken(AbstractRefreshToken):
|
||||
application = models.ForeignKey(
|
||||
|
||||
@@ -37,6 +37,8 @@ from collections import OrderedDict
|
||||
from django.core.exceptions import ValidationError
|
||||
from rest_framework import serializers
|
||||
|
||||
from pretix.api.auth.utils import get_session_key_for_api_request
|
||||
|
||||
|
||||
def remove_duplicates_from_list(data):
|
||||
return list(OrderedDict.fromkeys(data))
|
||||
@@ -83,10 +85,16 @@ class UploadedFileField(serializers.Field):
|
||||
request = self.context.get('request', None)
|
||||
try:
|
||||
cf = CachedFile.objects.get(
|
||||
session_key=f'api-upload-{str(type(request.user or request.auth))}-{(request.user or request.auth).pk}',
|
||||
file__isnull=False,
|
||||
pk=data[len("file:"):],
|
||||
)
|
||||
if cf.session_key == "api-upload-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-09, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_request(request):
|
||||
self.fail('not_found')
|
||||
except (ValidationError, IndexError): # invalid uuid
|
||||
self.fail('not_found')
|
||||
except CachedFile.DoesNotExist:
|
||||
|
||||
@@ -41,6 +41,7 @@ from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.relations import SlugRelatedField
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
from pretix.api.auth.utils import get_session_key_for_api_request
|
||||
from pretix.api.serializers import CompatDecimalField, CompatibleJSONField
|
||||
from pretix.api.serializers.event import SubEventSerializer
|
||||
from pretix.api.serializers.forms import form_field_to_serializer_field
|
||||
@@ -258,16 +259,21 @@ class AnswerSerializer(I18nAwareModelSerializer):
|
||||
if data['answer'] == 'file:keep':
|
||||
return data
|
||||
try:
|
||||
ao = self.context["request"].user or self.context["request"].auth
|
||||
cf = CachedFile.objects.get(
|
||||
session_key=f'api-upload-{str(type(ao))}-{ao.pk}',
|
||||
file__isnull=False,
|
||||
pk=data['answer'][len("file:"):],
|
||||
)
|
||||
if cf.session_key == "api-upload-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-09, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_request(self.context["request"]):
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
|
||||
except (ValidationError, IndexError): # invalid uuid
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
|
||||
except CachedFile.DoesNotExist:
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data['answer']))
|
||||
|
||||
allowed_types = (
|
||||
'image/png', 'image/jpeg', 'image/gif', 'application/pdf'
|
||||
@@ -1234,6 +1240,9 @@ class OrderCreateSerializer(I18nAwareModelSerializer):
|
||||
return None
|
||||
if pp not in self.context['event'].get_payment_providers():
|
||||
raise ValidationError('The given payment provider is not known.')
|
||||
if pp == "giftcard":
|
||||
raise serializers.ValidationError("Cannot create giftcard payment. Use `use_gift_cards` instead")
|
||||
|
||||
return pp
|
||||
|
||||
def validate_payment_info(self, info):
|
||||
@@ -1954,10 +1963,15 @@ class OrderPaymentCreateSerializer(I18nAwareModelSerializer):
|
||||
model = OrderPayment
|
||||
fields = ('state', 'amount', 'payment_date', 'provider', 'info')
|
||||
|
||||
def validate_provider(self, value):
|
||||
if value == "giftcard":
|
||||
raise serializers.ValidationError("Cannot create giftcard payment")
|
||||
return value
|
||||
|
||||
def create(self, validated_data):
|
||||
order = OrderPayment(order=self.context['order'], **validated_data)
|
||||
order.save()
|
||||
return order
|
||||
payment = OrderPayment(order=self.context['order'], **validated_data)
|
||||
payment.save()
|
||||
return payment
|
||||
|
||||
|
||||
class OrderRefundCreateSerializer(I18nAwareModelSerializer):
|
||||
@@ -1969,6 +1983,12 @@ class OrderRefundCreateSerializer(I18nAwareModelSerializer):
|
||||
model = OrderRefund
|
||||
fields = ('state', 'source', 'amount', 'payment', 'execution_date', 'provider', 'info', 'comment')
|
||||
|
||||
def validate_provider(self, value):
|
||||
if value == "giftcard":
|
||||
raise serializers.ValidationError("Cannot create giftcard payment")
|
||||
|
||||
return value
|
||||
|
||||
def create(self, validated_data):
|
||||
pid = validated_data.pop('payment', None)
|
||||
if pid:
|
||||
|
||||
@@ -40,9 +40,9 @@ from pretix.api.serializers.settings import SettingsSerializer
|
||||
from pretix.base.auth import get_auth_backends
|
||||
from pretix.base.i18n import get_language_without_region
|
||||
from pretix.base.models import (
|
||||
Customer, Device, GiftCard, GiftCardAcceptance, GiftCardTransaction,
|
||||
Membership, MembershipType, OrderPosition, Organizer, ReusableMedium,
|
||||
SalesChannel, SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
|
||||
Customer, Device, GiftCard, GiftCardTransaction, Membership,
|
||||
MembershipType, OrderPosition, Organizer, ReusableMedium, SalesChannel,
|
||||
SeatingPlan, Team, TeamAPIToken, TeamInvite, User,
|
||||
)
|
||||
from pretix.base.models.seating import SeatingPlanLayoutValidator
|
||||
from pretix.base.permissions import (
|
||||
@@ -268,15 +268,7 @@ class GiftCardSerializer(I18nAwareModelSerializer):
|
||||
data = super().validate(data)
|
||||
if 'secret' in data:
|
||||
s = data['secret']
|
||||
qs = GiftCard.objects.filter(
|
||||
secret=s
|
||||
).filter(
|
||||
Q(issuer=self.context["organizer"]) |
|
||||
Q(issuer__in=GiftCardAcceptance.objects.filter(
|
||||
acceptor=self.context["organizer"],
|
||||
active=True,
|
||||
).values_list('issuer', flat=True))
|
||||
)
|
||||
qs = self.context["organizer"].accepted_gift_cards.filter(secret=s)
|
||||
if self.instance:
|
||||
qs = qs.exclude(pk=self.instance.pk)
|
||||
if qs.exists():
|
||||
|
||||
@@ -50,6 +50,7 @@ from rest_framework.generics import ListAPIView
|
||||
from rest_framework.permissions import SAFE_METHODS
|
||||
from rest_framework.response import Response
|
||||
|
||||
from pretix.api.auth.utils import get_session_key_for_api_auth
|
||||
from pretix.api.serializers.checkin import (
|
||||
CheckinListSerializer, CheckinRPCAnnulInputSerializer,
|
||||
CheckinRPCRedeemInputSerializer, MiniCheckinListSerializer,
|
||||
@@ -329,10 +330,16 @@ with scopes_disabled():
|
||||
def _handle_file_upload(data, user, auth):
|
||||
try:
|
||||
cf = CachedFile.objects.get(
|
||||
session_key=f'api-upload-{str(type(user or auth))}-{(user or auth).pk}',
|
||||
file__isnull=False,
|
||||
pk=data[len("file:"):],
|
||||
)
|
||||
if cf.session_key == "api-upload-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-09, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_auth(user, auth):
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except (ValidationError, BaseValidationError, IndexError): # invalid uuid
|
||||
raise ValidationError('The submitted file ID "{fid}" was not found.'.format(fid=data))
|
||||
except CachedFile.DoesNotExist:
|
||||
|
||||
@@ -73,7 +73,7 @@ class ExportersMixin:
|
||||
|
||||
@action(detail=True, methods=['GET'], url_name='download', url_path='download/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def download(self, *args, **kwargs):
|
||||
cf = get_object_or_404(CachedFile, id=kwargs['cfid'])
|
||||
cf = get_object_or_404(CachedFile, id=kwargs['cfid'], web_download=True)
|
||||
if not cf.allowed_for_session(self.request, "exporters-api"):
|
||||
return Response(
|
||||
{'status': 'failed', 'message': 'Unknown file ID or export failed'},
|
||||
|
||||
@@ -39,7 +39,7 @@ from pretix.api.serializers.media import (
|
||||
)
|
||||
from pretix.base.media import MEDIA_TYPES
|
||||
from pretix.base.models import (
|
||||
Checkin, GiftCard, GiftCardAcceptance, GiftCardTransaction, OrderPosition,
|
||||
Checkin, GiftCardAcceptance, GiftCardTransaction, OrderPosition,
|
||||
ReusableMedium,
|
||||
)
|
||||
from pretix.base.models.orders import PrintLog
|
||||
@@ -88,7 +88,7 @@ class ReusableMediaViewSet(viewsets.ModelViewSet):
|
||||
),
|
||||
Prefetch(
|
||||
'linked_giftcard',
|
||||
queryset=GiftCard.objects.annotate(
|
||||
queryset=self.request.organizer.accepted_gift_cards.annotate(
|
||||
cached_value=Coalesce(Subquery(s), Decimal('0.00'))
|
||||
)
|
||||
)
|
||||
|
||||
@@ -33,6 +33,7 @@ from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
from pretix.api.auth.utils import get_session_key_for_api_request
|
||||
from pretix.api.serializers.shredders import (
|
||||
JobRunSerializer, ShredderSerializer,
|
||||
)
|
||||
@@ -68,8 +69,14 @@ class ShreddersMixin:
|
||||
cf = get_object_or_404(
|
||||
CachedFile,
|
||||
id=kwargs['cfid'],
|
||||
session_key=f'api-shredder-{str(type(self.request.user or self.request.auth))}-{(self.request.user or self.request.auth).pk}'
|
||||
)
|
||||
if cf.session_key == "api-shredder-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-10, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_request(self.request, prefix='api-shredder'):
|
||||
raise Http404()
|
||||
if cf.file:
|
||||
resp = ChunkBasedFileResponse(cf.file.file, content_type=cf.type)
|
||||
resp['Content-Disposition'] = 'attachment; filename="{}"'.format(cf.filename).encode("ascii", "ignore")
|
||||
@@ -118,10 +125,16 @@ class ShreddersMixin:
|
||||
)
|
||||
|
||||
try:
|
||||
CachedFile.objects.get(
|
||||
cf = CachedFile.objects.get(
|
||||
id=kwargs['cfid'],
|
||||
session_key=f'api-shredder-{str(type(self.request.user or self.request.auth))}-{(self.request.user or self.request.auth).pk}'
|
||||
)
|
||||
if cf.session_key == "api-shredder-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-10, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_request(self.request, prefix='api-shredder'):
|
||||
raise CachedFile.DoesNotExist()
|
||||
except CachedFile.DoesNotExist:
|
||||
return Response(
|
||||
{'status': 'gone', 'message': 'May have succeeded or timed out'},
|
||||
@@ -140,8 +153,14 @@ class ShreddersMixin:
|
||||
cf = get_object_or_404(
|
||||
CachedFile,
|
||||
id=kwargs['cfid'],
|
||||
session_key=f'api-shredder-{str(type(self.request.user or self.request.auth))}-{(self.request.user or self.request.auth).pk}'
|
||||
)
|
||||
if cf.session_key == "api-shredder-<class 'django.contrib.auth.models.AnonymousUser'>-None":
|
||||
# OK, backwards-compatibility of a security bug fixed 2026-10, delete this at some point, but should
|
||||
# also be harmless because all files with this key are expired one day after deployment of this fix
|
||||
# and no new files with this key are created
|
||||
pass
|
||||
elif cf.session_key != get_session_key_for_api_request(self.request, prefix='api-shredder'):
|
||||
raise Http404()
|
||||
if cf.file:
|
||||
async_result = self.do_shred(cf)
|
||||
url_kwargs = {
|
||||
@@ -184,7 +203,7 @@ class ShreddersMixin:
|
||||
cf = CachedFile(web_download=False)
|
||||
cf.date = now()
|
||||
cf.expires = now() + timedelta(hours=2)
|
||||
cf.session_key = f'api-shredder-{str(type(self.request.user or self.request.auth))}-{(self.request.user or self.request.auth).pk}'
|
||||
cf.session_key = get_session_key_for_api_request(self.request, prefix='api-shredder')
|
||||
cf.save()
|
||||
d = serializer.data
|
||||
for k, v in d.items():
|
||||
@@ -224,7 +243,7 @@ class EventShreddersViewSet(ShreddersMixin, viewsets.ViewSet):
|
||||
return export.apply_async(args=(
|
||||
self.request.event.id,
|
||||
list(shredders),
|
||||
f'api-shredder-{str(type(self.request.user or self.request.auth))}-{(self.request.user or self.request.auth).pk}',
|
||||
get_session_key_for_api_request(self.request, prefix='api-shredder'),
|
||||
str(cf.pk)
|
||||
))
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ from rest_framework.views import APIView
|
||||
from pretix.api.auth.device import DeviceTokenAuthentication
|
||||
from pretix.api.auth.permission import AnyAuthenticatedClientPermission
|
||||
from pretix.api.auth.token import TeamTokenAuthentication
|
||||
from pretix.api.auth.utils import get_session_key_for_api_request
|
||||
from pretix.base.models import CachedFile
|
||||
from pretix.helpers.images import (
|
||||
IMAGE_TYPES, validate_uploaded_file_for_valid_image,
|
||||
@@ -78,7 +79,7 @@ class UploadView(APIView):
|
||||
web_download=False,
|
||||
filename=file_obj.name,
|
||||
type=content_type,
|
||||
session_key=f'api-upload-{str(type(request.user or request.auth))}-{(request.user or request.auth).pk}'
|
||||
session_key=get_session_key_for_api_request(request)
|
||||
)
|
||||
cf.file.save(file_obj.name, file_obj)
|
||||
cf.save()
|
||||
|
||||
@@ -55,9 +55,10 @@ from openpyxl.comments import Comment
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
|
||||
from pretix.base.models import (
|
||||
Checkin, GiftCard, GiftCardTransaction, Invoice, InvoiceAddress, Order,
|
||||
Checkin, GiftCardTransaction, Invoice, InvoiceAddress, Order,
|
||||
OrderPosition, Question,
|
||||
)
|
||||
from pretix.base.models.giftcards import GiftCard
|
||||
from pretix.base.models.orders import (
|
||||
OrderFee, OrderPayment, OrderRefund, Transaction,
|
||||
)
|
||||
@@ -1326,12 +1327,12 @@ class GiftcardRedemptionListExporter(ListExporter):
|
||||
order__event__in=self.events,
|
||||
provider='giftcard',
|
||||
state__in=(OrderPayment.PAYMENT_STATE_CONFIRMED, OrderPayment.PAYMENT_STATE_REFUNDED),
|
||||
).order_by('created')
|
||||
).order_by('created').select_related("order__event__organizer")
|
||||
refunds = OrderRefund.objects.filter(
|
||||
order__event__in=self.events,
|
||||
provider='giftcard',
|
||||
state=OrderRefund.REFUND_STATE_DONE
|
||||
).order_by('created')
|
||||
).order_by('created').select_related("order__event__organizer")
|
||||
|
||||
objs = sorted(list(payments) + list(refunds), key=lambda o: (o.order.code, o.created))
|
||||
|
||||
@@ -1348,9 +1349,9 @@ class GiftcardRedemptionListExporter(ListExporter):
|
||||
obj.order.code,
|
||||
obj.full_id,
|
||||
obj.created.astimezone(tz).date().strftime('%Y-%m-%d'),
|
||||
gc.secret,
|
||||
gc.secret if gc.accepted_by(obj.order.event.organizer) else '?',
|
||||
obj.amount * (-1 if isinstance(obj, OrderRefund) else 1),
|
||||
gc.issuer
|
||||
gc.issuer.slug
|
||||
]
|
||||
yield row
|
||||
|
||||
|
||||
@@ -593,12 +593,16 @@ class PortraitImageField(SizeValidationMixin, ExtValidationMixin, forms.FileFiel
|
||||
image = ImageOps.exif_transpose(image)
|
||||
|
||||
if f._cropdata:
|
||||
image = image.crop((
|
||||
f._cropdata.get('x', 0),
|
||||
f._cropdata.get('y', 0),
|
||||
f._cropdata.get('x', 0) + f._cropdata.get('width', image.width),
|
||||
f._cropdata.get('y', 0) + f._cropdata.get('height', image.height),
|
||||
))
|
||||
left = int(f._cropdata.get('x', 0))
|
||||
top = int(f._cropdata.get('y', 0))
|
||||
right = left + int(f._cropdata.get('width', image.width))
|
||||
bottom = top + int(f._cropdata.get('height', image.height))
|
||||
if left >= image.width or top >= image.height or right > image.width or bottom > image.height:
|
||||
raise ValidationError(
|
||||
self.error_messages['max_dimension'],
|
||||
code='max_dimension',
|
||||
)
|
||||
image = image.crop((left, top, right, bottom))
|
||||
with BytesIO() as output:
|
||||
# This might use a lot of memory, but temporary files are not a good option since
|
||||
# we don't control the cleanup
|
||||
|
||||
@@ -1050,10 +1050,8 @@ class Item(LoggedModel):
|
||||
|
||||
replace_year = valid_until.year
|
||||
replace_month = valid_until.month + self.validity_dynamic_duration_months
|
||||
|
||||
while replace_month > 12:
|
||||
replace_month -= 12
|
||||
replace_year += 1
|
||||
replace_year += (replace_month - 1) // 12
|
||||
replace_month = ((replace_month - 1) % 12) + 1
|
||||
max_day = calendar.monthrange(replace_year, replace_month)[1]
|
||||
replace_date = date(
|
||||
year=replace_year,
|
||||
|
||||
+35
-29
@@ -1510,42 +1510,37 @@ class GiftCardPayment(BasePaymentProvider):
|
||||
})
|
||||
|
||||
def refund_control_render(self, request, refund) -> str:
|
||||
from .models import GiftCard
|
||||
|
||||
if 'gift_card' in refund.info_data:
|
||||
gc = GiftCard.objects.get(pk=refund.info_data.get('gift_card'))
|
||||
template = get_template('pretixcontrol/giftcards/payment.html')
|
||||
|
||||
ctx = {
|
||||
'request': request,
|
||||
'event': self.event,
|
||||
'gc': gc,
|
||||
}
|
||||
try:
|
||||
gc = self.event.organizer.accepted_gift_cards.get(pk=refund.info_data.get('gift_card'))
|
||||
ctx['gc'] = gc
|
||||
except GiftCard.DoesNotExist:
|
||||
pass
|
||||
return template.render(ctx)
|
||||
|
||||
def payment_control_render(self, request, payment) -> str:
|
||||
from .models import GiftCard
|
||||
template = get_template('pretixcontrol/giftcards/payment.html')
|
||||
ctx = {
|
||||
'request': request,
|
||||
'event': self.event,
|
||||
**({'error': payment.info_data[
|
||||
'error']} if 'error' in payment.info_data else {}),
|
||||
**({'gift_card_secret': payment.info_data[
|
||||
'gift_card_secret']} if 'gift_card_secret' in payment.info_data else {})
|
||||
}
|
||||
|
||||
if any(key in payment.info_data for key in ('gift_card', 'error')):
|
||||
template = get_template('pretixcontrol/giftcards/payment.html')
|
||||
ctx = {
|
||||
'request': request,
|
||||
'event': self.event,
|
||||
**({'error': payment.info_data[
|
||||
'error']} if 'error' in payment.info_data else {}),
|
||||
**({'gift_card_secret': payment.info_data[
|
||||
'gift_card_secret']} if 'gift_card_secret' in payment.info_data else {})
|
||||
}
|
||||
try:
|
||||
ctx['gc'] = self.event.organizer.accepted_gift_cards.get(pk=payment.info_data.get('gift_card'))
|
||||
except GiftCard.DoesNotExist:
|
||||
pass
|
||||
|
||||
try:
|
||||
gc = GiftCard.objects.get(pk=payment.info_data.get('gift_card'))
|
||||
ctx = {
|
||||
'gc': gc,
|
||||
}
|
||||
except GiftCard.DoesNotExist:
|
||||
pass
|
||||
finally:
|
||||
return template.render(ctx)
|
||||
if any(key in ctx for key in ('gc', 'gift_card_secret', 'error')):
|
||||
return template.render(ctx)
|
||||
|
||||
def payment_control_render_short(self, payment: OrderPayment) -> str:
|
||||
d = payment.info_data
|
||||
@@ -1555,10 +1550,9 @@ class GiftCardPayment(BasePaymentProvider):
|
||||
d = refund.info_data
|
||||
return d.get('gift_card_secret', d.get('gift_card_code', self.public_name))
|
||||
|
||||
def api_payment_details(self, payment: OrderPayment):
|
||||
from .models import GiftCard
|
||||
def api_payment_details(self, payment: OrderPayment | OrderRefund):
|
||||
try:
|
||||
gc = GiftCard.objects.get(pk=payment.info_data.get('gift_card'))
|
||||
gc = self.event.organizer.accepted_gift_cards.get(pk=payment.info_data.get('gift_card'))
|
||||
except GiftCard.DoesNotExist:
|
||||
return {
|
||||
**({'error': payment.info_data[
|
||||
@@ -1681,7 +1675,19 @@ class GiftCardPayment(BasePaymentProvider):
|
||||
@transaction.atomic()
|
||||
def execute_refund(self, refund: OrderRefund):
|
||||
from .models import GiftCard
|
||||
gc = GiftCard.objects.get(pk=refund.info_data.get('gift_card') or refund.payment.info_data.get('gift_card'))
|
||||
try:
|
||||
gc = self.event.organizer.accepted_gift_cards.get(
|
||||
pk=refund.info_data.get('gift_card') or refund.payment.info_data.get('gift_card'),
|
||||
currency=self.event.currency
|
||||
)
|
||||
except GiftCard.DoesNotExist:
|
||||
raise PaymentException(_("Gift card not found."))
|
||||
|
||||
if gc.testmode != refund.order.testmode:
|
||||
raise PaymentException(_("Only test gift card can be used in test mode and vice versa."))
|
||||
if gc.expires and gc.expires < time_machine_now():
|
||||
raise PaymentException(_("This gift card is no longer valid."))
|
||||
|
||||
trans = gc.transactions.create(
|
||||
value=refund.amount,
|
||||
order=refund.order,
|
||||
|
||||
@@ -1079,7 +1079,7 @@ class Renderer:
|
||||
fontsize = float(o['fontsize'])
|
||||
height = float(o['height']) * mm
|
||||
width = float(o['width']) * mm
|
||||
while True:
|
||||
for _i in range(25): # try adapting the font size at most 25 times
|
||||
p, ad, lineheight = self._text_paragraph(op, order, o, override_fontsize=fontsize)
|
||||
w, h = p.wrapOn(canvas, width, 1000 * mm)
|
||||
widths = p.getActualLineWidths0()
|
||||
|
||||
@@ -969,7 +969,7 @@ def _apply_rounding_and_fees(positions: List[CartPosition], payment_requests: Li
|
||||
gift_cards = [] # for backwards compatibility
|
||||
for p in payment_requests:
|
||||
if p['provider'] == 'giftcard':
|
||||
gift_cards.append(GiftCard.objects.get(pk=p['info_data']['gift_card']))
|
||||
gift_cards.extend(event.organizer.accepted_gift_cards.filter(pk=p['info_data']['gift_card']))
|
||||
|
||||
for recv, resp in order_fee_calculation.send(sender=event, invoice_address=address, total=total, payment_requests=payment_requests,
|
||||
meta_info=meta_info, positions=positions, gift_cards=gift_cards):
|
||||
|
||||
@@ -172,7 +172,9 @@ class CachedFileInput(forms.ClearableFileInput):
|
||||
from ...base.models import CachedFile
|
||||
v = super().value_from_datadict(data, files, name)
|
||||
if v is None and data.get(name + '-cachedfile'): # An explicit "[x] clear" would be False, not None
|
||||
return CachedFile.objects.filter(id=data[name + '-cachedfile']).first()
|
||||
v = CachedFile.objects.filter(id=data[name + '-cachedfile'], web_download=True).first()
|
||||
if not v.allowed_for_session(self.request):
|
||||
v = None
|
||||
return v
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
|
||||
@@ -836,9 +836,10 @@ class CancelSettingsForm(SettingsForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.obj.settings.giftcard_expiry_years is not None:
|
||||
self.fields['cancel_allow_user_paid_refund_as_giftcard'].help_text = gettext(
|
||||
'You have configured gift cards to be valid {} years plus the year the gift card is issued in.'
|
||||
).format(self.obj.settings.giftcard_expiry_years)
|
||||
self.fields['cancel_allow_user_paid_refund_as_giftcard'].help_text = format_html(
|
||||
gettext('You have configured gift cards to be valid {} years plus the year the gift card is issued in.'),
|
||||
self.obj.settings.giftcard_expiry_years
|
||||
)
|
||||
|
||||
|
||||
class PaymentSettingsForm(EventSettingsValidationMixin, SettingsForm):
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
from django import forms
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.functional import lazy
|
||||
from django.utils.html import format_html
|
||||
from django.utils.html import conditional_escape, format_html
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from pretix.base.modelimport_orders import get_order_import_columns
|
||||
@@ -66,7 +66,7 @@ class ProcessForm(forms.Form):
|
||||
widget=forms.Select(
|
||||
attrs={'data-static': 'true'}
|
||||
),
|
||||
help_text=c.help_text,
|
||||
help_text=conditional_escape(c.help_text),
|
||||
)
|
||||
|
||||
def get_columns(self):
|
||||
|
||||
@@ -38,7 +38,6 @@ from urllib.parse import urlparse
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models import Q
|
||||
from django.forms import formset_factory, inlineformset_factory
|
||||
from django.forms.utils import ErrorDict
|
||||
from django.urls import reverse
|
||||
@@ -70,9 +69,9 @@ from pretix.base.forms.widgets import (
|
||||
SplitDateTimePickerWidget, format_placeholders_help_text,
|
||||
)
|
||||
from pretix.base.models import (
|
||||
Customer, Device, Event, EventMetaProperty, Gate, GiftCard,
|
||||
GiftCardAcceptance, Membership, MembershipType, OrderPosition, Organizer,
|
||||
ReusableMedium, SalesChannel, Team,
|
||||
Customer, Device, Event, EventMetaProperty, Gate, GiftCard, Membership,
|
||||
MembershipType, OrderPosition, Organizer, ReusableMedium, SalesChannel,
|
||||
Team,
|
||||
)
|
||||
from pretix.base.models.customers import CustomerSSOClient, CustomerSSOProvider
|
||||
from pretix.base.models.organizer import OrganizerFooterLink, TeamQuerySet
|
||||
@@ -364,7 +363,7 @@ class TeamForm(forms.ModelForm):
|
||||
for opt in pg.options
|
||||
],
|
||||
label=pg.label,
|
||||
help_text=pg.help_text,
|
||||
help_text=conditional_escape(pg.help_text),
|
||||
initial=initial,
|
||||
widget=forms.RadioSelect,
|
||||
)
|
||||
@@ -389,7 +388,7 @@ class TeamForm(forms.ModelForm):
|
||||
for opt in pg.options
|
||||
],
|
||||
label=pg.label,
|
||||
help_text=pg.help_text,
|
||||
help_text=conditional_escape(pg.help_text),
|
||||
initial=initial,
|
||||
widget=forms.RadioSelect,
|
||||
)
|
||||
@@ -894,15 +893,7 @@ class GiftCardCreateForm(forms.ModelForm):
|
||||
|
||||
def clean_secret(self):
|
||||
s = self.cleaned_data['secret']
|
||||
if GiftCard.objects.filter(
|
||||
secret__iexact=s
|
||||
).filter(
|
||||
Q(issuer=self.organizer) |
|
||||
Q(issuer__in=GiftCardAcceptance.objects.filter(
|
||||
acceptor=self.organizer,
|
||||
active=True,
|
||||
).values_list('issuer', flat=True))
|
||||
).exists():
|
||||
if self.organizer.accepted_gift_cards.filter(secret__iexact=s).exists():
|
||||
raise ValidationError(
|
||||
_('A gift card with the same secret already exists in your or an affiliated organizer account.')
|
||||
)
|
||||
|
||||
@@ -44,6 +44,7 @@ from django.db.models import Count, F, Max
|
||||
from django.db.models.functions import Upper
|
||||
from django.forms.utils import ErrorDict
|
||||
from django.urls import reverse
|
||||
from django.utils.html import escape
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext_lazy as _, pgettext_lazy
|
||||
from django_scopes.forms import SafeModelChoiceField
|
||||
@@ -176,7 +177,7 @@ class VoucherForm(I18nModelForm):
|
||||
required=False,
|
||||
widget=forms.TextInput(attrs={'data-seat-guid-field': '1'}),
|
||||
initial=self.instance.seat.seat_guid if self.instance.seat else '',
|
||||
help_text=str(self.instance.seat) if self.instance.seat else '',
|
||||
help_text=escape(str(self.instance.seat) if self.instance.seat else ''),
|
||||
)
|
||||
|
||||
def parse_itemvar(self, data):
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
{% load i18n %}
|
||||
|
||||
<dl class="dl-horizontal">
|
||||
<dt>{% trans "Gift card code" %}</dt>
|
||||
<dd>
|
||||
{% if gc %}
|
||||
<a href="{% url "control:organizer.giftcard" organizer=gc.issuer.slug giftcard=gc.pk %}">
|
||||
{{ gc.secret }}
|
||||
</a>
|
||||
{% if gc.issuer.slug != request.organizer %}
|
||||
<span class="text-muted">
|
||||
<br>
|
||||
<span class="fa fa-group"></span> {{ gc.issuer }}
|
||||
</span>
|
||||
{% if gc or gift_card_secret %}
|
||||
<dt>{% trans "Gift card code" %}</dt>
|
||||
<dd>
|
||||
{% if gc %}
|
||||
<a href="{% url "control:organizer.giftcard" organizer=gc.issuer.slug giftcard=gc.pk %}">
|
||||
{{ gc.secret }}
|
||||
</a>
|
||||
{% if gc.issuer.slug != request.organizer %}
|
||||
<span class="text-muted">
|
||||
<br>
|
||||
<span class="fa fa-group"></span> {{ gc.issuer }}
|
||||
</span>
|
||||
{% endif %}
|
||||
{% elif gift_card_secret %}
|
||||
{{ gift_card_secret }}
|
||||
{% endif %}
|
||||
{% elif gift_card_secret %}
|
||||
{{ gift_card_secret }}
|
||||
{% endif %}
|
||||
</dd>
|
||||
</dd>
|
||||
{% endif %}
|
||||
{% if gc %}
|
||||
<dt>{% trans "Issuer" %}</dt>
|
||||
<dd>{{ gc.issuer }}</dd>
|
||||
@@ -25,4 +27,4 @@
|
||||
<dt>{% trans "Error" %}</dt>
|
||||
<dd>{{ error }}</dd>
|
||||
{% endif %}
|
||||
</dl>
|
||||
</dl>
|
||||
@@ -402,9 +402,12 @@ def event_index_widgets_lazy(request, organizer, event):
|
||||
except SubEvent.DoesNotExist:
|
||||
pass
|
||||
|
||||
can_view_orders = request.user.has_event_permission(request.organizer, request.event, 'event.orders:read',
|
||||
request=request)
|
||||
widgets = []
|
||||
for r, result in event_dashboard_widgets.send(sender=request.event, subevent=subevent, lazy=False):
|
||||
widgets.extend(result)
|
||||
if can_view_orders:
|
||||
for r, result in event_dashboard_widgets.send(sender=request.event, subevent=subevent, lazy=False):
|
||||
widgets.extend(result)
|
||||
|
||||
return build_json_response(widgets)
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ from decimal import Decimal
|
||||
from io import BytesIO
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.files import File
|
||||
from django.core.files.base import ContentFile
|
||||
from django.core.files.storage import default_storage
|
||||
@@ -247,6 +248,8 @@ class BaseEditorView(EventPermissionRequiredMixin, TemplateView):
|
||||
if request.POST.get("background", "").strip():
|
||||
try:
|
||||
cf = CachedFile.objects.get(id=request.POST.get("background"), web_download=True)
|
||||
if not cf.allowed_for_session(request, "ticketoutput-pdf-background"):
|
||||
cf = None
|
||||
except CachedFile.DoesNotExist:
|
||||
pass
|
||||
|
||||
@@ -302,6 +305,8 @@ class FontsCSSView(TemplateView):
|
||||
|
||||
class PdfView(TemplateView):
|
||||
def get(self, request, *args, **kwargs):
|
||||
cf = get_object_or_404(CachedFile, id=kwargs.get("filename"), filename="background_preview.pdf")
|
||||
cf = get_object_or_404(CachedFile, id=kwargs.get("filename"), filename="background_preview.pdf", web_download=True)
|
||||
if not cf.allowed_for_session(request, "ticketoutput-pdf-background"):
|
||||
raise PermissionDenied()
|
||||
resp = FileResponse(cf.file, filename=cf.filename, content_type='application/pdf')
|
||||
return resp
|
||||
@@ -242,6 +242,13 @@ def monkeypatch_reportlab_imagereader():
|
||||
utils.ImageReader.__init__ = new_init
|
||||
|
||||
|
||||
def monkeypatch_json_constants():
|
||||
from json.decoder import _CONSTANTS # noqa
|
||||
del _CONSTANTS['-Infinity']
|
||||
del _CONSTANTS['Infinity']
|
||||
del _CONSTANTS['NaN']
|
||||
|
||||
|
||||
def monkeypatch_all_at_ready():
|
||||
monkeypatch_vobject_performance()
|
||||
monkeypatch_pillow_safer()
|
||||
@@ -249,3 +256,4 @@ def monkeypatch_all_at_ready():
|
||||
monkeypatch_urllib3_ssrf_protection()
|
||||
monkeypatch_cookie_morsel()
|
||||
monkeypatch_reportlab_imagereader()
|
||||
monkeypatch_json_constants()
|
||||
@@ -228,7 +228,7 @@ class TicketRendererViewSet(viewsets.ViewSet):
|
||||
|
||||
@action(detail=False, methods=['GET'], url_name='download', url_path='download/(?P<asyncid>[^/]+)/(?P<cfid>[^/]+)')
|
||||
def download(self, *args, **kwargs):
|
||||
cf = get_object_or_404(CachedFile, id=kwargs['cfid'])
|
||||
cf = get_object_or_404(CachedFile, id=kwargs['cfid'], web_download=True)
|
||||
if not cf.allowed_for_session(self.request, "ticketoutputpdf-api"):
|
||||
return Response(
|
||||
{'status': 'failed', 'message': 'Unknown file ID or export failed'},
|
||||
@@ -269,7 +269,7 @@ class TicketRendererViewSet(viewsets.ViewSet):
|
||||
})
|
||||
serializer.is_valid(raise_exception=True)
|
||||
|
||||
cf = CachedFile(web_download=False)
|
||||
cf = CachedFile(web_download=True)
|
||||
cf.bind_to_session(self.request, "ticketoutputpdf-api")
|
||||
cf.date = now()
|
||||
cf.expires = now() + timedelta(hours=24)
|
||||
|
||||
@@ -30,7 +30,8 @@ from django.contrib.auth.password_validation import (
|
||||
)
|
||||
from django.contrib.auth.tokens import PasswordResetTokenGenerator
|
||||
from django.core import signing
|
||||
from django.utils.html import escape
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.html import escape, format_html
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from phonenumber_field.formfields import PhoneNumberField
|
||||
|
||||
@@ -81,7 +82,8 @@ class AuthenticationForm(forms.Form):
|
||||
self.request = request
|
||||
self.customer_cache = None
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['password'].help_text = "<a target='_blank' href='{}'>{}</a>".format(
|
||||
self.fields['password'].help_text = format_html(
|
||||
"<a target='_blank' href='{}'>{}</a>",
|
||||
eventreverse_absolute(False, 'presale:organizer.customer.resetpw', kwargs={
|
||||
'organizer': request.organizer.slug,
|
||||
}),
|
||||
|
||||
@@ -14,10 +14,23 @@
|
||||
{% trans "Log out" %}
|
||||
</a>
|
||||
{% else %}
|
||||
<a href="{% abseventurl request.organizer "presale:organizer.customer.login" %}{% if request.resolver_match.url_name != "organizer.customer.login" %}?next={% if request.event_domain %}{{ request.scheme }}://{{ request.get_host }}{% endif %}{{ request.path|urlencode }}%3F{{ request.META.QUERY_STRING|urlencode }}{% endif %}{% if request.event_domain %}&request_cross_domain_customer_auth=true{% endif %}">
|
||||
<span class="fa fa-sign-in" aria-hidden="true"></span>
|
||||
{% trans "Log in" %}</a>
|
||||
|
||||
<form
|
||||
{% if request.event_domain %}
|
||||
action="{% abseventurl request.event "presale:event.customer.loginstart" %}" method="post"
|
||||
{% else %}
|
||||
action="{% abseventurl request.organizer "presale:organizer.customer.login" %}" method="get"
|
||||
{% endif %}
|
||||
class="helper-display-inline">
|
||||
{% if request.event_domain %}
|
||||
{% csrf_token %}
|
||||
{% endif %}
|
||||
{% if request.resolver_match.url_name != "organizer.customer.login" %}
|
||||
<input type="hidden" name="next" value="{% if request.event_domain %}{{ request.scheme }}://{{ request.get_host }}{% endif %}{{ request.path }}?{{ request.META.QUERY_STRING }}">
|
||||
{% endif %}
|
||||
<button class="btn btn-link" type="submit">
|
||||
<span class="fa fa-sign-in" aria-hidden="true"></span>
|
||||
{% trans "Log in" %}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</nav>
|
||||
{% endif %}
|
||||
@@ -98,6 +98,7 @@ event_patterns = [
|
||||
re_path(r'unlock/(?P<hash>[a-z0-9]{64})/$', pretix.presale.views.user.UnlockHashView.as_view(),
|
||||
name='event.payment.unlock'),
|
||||
re_path(r'resend/$', pretix.presale.views.user.ResendLinkView.as_view(), name='event.resend_link'),
|
||||
re_path(r'^account/loginstart$', pretix.presale.views.customer.LoginStartView.as_view(), name='event.customer.loginstart'),
|
||||
|
||||
re_path(r'^favicon.ico/?$',
|
||||
pretix.presale.views.organizer.OrganizerFavicon.as_view(),
|
||||
|
||||
@@ -151,7 +151,9 @@ def add_customer_to_request(request):
|
||||
else:
|
||||
parent_session_key = otpstore.get(f'customer_cross_domain_auth_{request.organizer.pk}')
|
||||
|
||||
if parent_session_key: # not already invalidated, expired, …
|
||||
expected_nonce = request.session.pop('cross_domain_customer_auth_nonce', None)
|
||||
found_nonce = request.GET.get("cross_domain_customer_auth_nonce")
|
||||
if parent_session_key and expected_nonce and expected_nonce == found_nonce: # not already invalidated, expired, …
|
||||
# Make sure the OTP can't be used again
|
||||
otpstore.delete()
|
||||
|
||||
|
||||
@@ -450,7 +450,7 @@ class CartApplyVoucher(EventViewMixin, CartActionMixin, AsyncAction, View):
|
||||
|
||||
if not self.request.event.vouchers.filter(code__iexact=code):
|
||||
try:
|
||||
gc = self.request.event.organizer.accepted_gift_cards.get(secret=code)
|
||||
gc = self.request.organizer.accepted_gift_cards.get(secret=code)
|
||||
gcp = GiftCardPayment(self.request.event)
|
||||
if not gcp.is_enabled or not gcp.is_allowed(self.request, Decimal("1.00")):
|
||||
raise ValidationError(error_messages['voucher_invalid'])
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
#
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.core.exceptions import SuspiciousOperation
|
||||
from django.http import Http404
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
@@ -29,6 +31,7 @@ from django.views.generic import View
|
||||
|
||||
from pretix.base.services.cart import CartError
|
||||
from pretix.base.signals import validate_cart
|
||||
from pretix.base.views.tasks import AsyncAction
|
||||
from pretix.helpers.http import redirect_to_url
|
||||
from pretix.multidomain.urlreverse import eventreverse
|
||||
from pretix.presale.checkoutflow import get_checkout_flow
|
||||
@@ -51,7 +54,12 @@ class CheckoutView(View):
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.request = request
|
||||
|
||||
if not cart_exists(request) and "async_id" not in request.GET:
|
||||
is_asyncaction_call = (
|
||||
request.method == "GET" and
|
||||
'async_id' in request.GET and
|
||||
settings.HAS_CELERY
|
||||
)
|
||||
if not cart_exists(request) and not is_asyncaction_call:
|
||||
messages.error(request, _("Your cart is empty"))
|
||||
return self.redirect(self.get_index_url(self.request))
|
||||
|
||||
@@ -78,9 +86,13 @@ class CheckoutView(View):
|
||||
utm_params = {k: v for k, v in request.GET.items() if k.startswith("utm_")}
|
||||
return self.redirect(step.get_step_url(request) + '?' + urlencode(utm_params))
|
||||
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):
|
||||
|
||||
if not is_asyncaction_call and not is_selected and not step.is_completed(request, warn=not is_selected):
|
||||
return self.redirect(step.get_step_url(request))
|
||||
if is_selected:
|
||||
if is_asyncaction_call and not isinstance(step, AsyncAction):
|
||||
# This could be used to circumvent validation otherwise
|
||||
raise SuspiciousOperation("Received ?async_id for a step that is not an AsyncAction")
|
||||
if request.method.lower() in self.http_method_names:
|
||||
handler = getattr(step, request.method.lower(), self.http_method_not_allowed)
|
||||
else:
|
||||
|
||||
@@ -146,6 +146,7 @@ class LoginView(RedirectBackMixin, FormView):
|
||||
u = urlparse(url)
|
||||
qsl = parse_qs(u.query)
|
||||
qsl['cross_domain_customer_auth'] = otp
|
||||
qsl['cross_domain_customer_auth_nonce'] = self.request.GET.get("request_cross_domain_customer_auth_nonce", "")
|
||||
url = urlunparse((u.scheme, u.netloc, u.path, u.params, urlencode(qsl, doseq=True), u.fragment))
|
||||
|
||||
return url
|
||||
@@ -699,6 +700,7 @@ class SSOLoginView(RedirectBackMixin, View):
|
||||
request.session[f'pretix_customerauth_{self.provider.pk}_nonce'] = nonce
|
||||
request.session[f'pretix_customerauth_{self.provider.pk}_popup_origin'] = popup_origin
|
||||
request.session[f'pretix_customerauth_{self.provider.pk}_cross_domain_requested'] = self.request.GET.get("request_cross_domain_customer_auth") == "true"
|
||||
request.session[f'pretix_customerauth_{self.provider.pk}_cross_domain_nonce'] = self.request.GET.get("request_cross_domain_customer_auth_nonce")
|
||||
redirect_uri = eventreverse_absolute(self.request.organizer, 'presale:organizer.customer.login.return', kwargs={
|
||||
'provider': self.provider.pk
|
||||
})
|
||||
@@ -946,6 +948,28 @@ class SSOLoginReturnView(RedirectBackMixin, View):
|
||||
u = urlparse(url)
|
||||
qsl = parse_qs(u.query)
|
||||
qsl['cross_domain_customer_auth'] = otp
|
||||
qsl['cross_domain_customer_auth_nonce'] = self.request.session.get(f'pretix_customerauth_{self.provider.pk}_cross_domain_nonce', '')
|
||||
url = urlunparse((u.scheme, u.netloc, u.path, u.params, urlencode(qsl, doseq=True), u.fragment))
|
||||
|
||||
return url
|
||||
|
||||
|
||||
class LoginStartView(View):
|
||||
# When a login is initiated on a event-domain-level view, we need to carry the user to the organizer domain through
|
||||
# this POST request to be able to set a nonce on their current session. We can't just use a link, since then we'd
|
||||
# need to create sessions for every anonymous user of the ticketshop, which is too expensive.
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
if getattr(self.request, 'domain_mode', 'system') not in (KnownDomain.MODE_ORG_ALT_DOMAIN, KnownDomain.MODE_EVENT_DOMAIN):
|
||||
raise Http404("Only active on event-level domains")
|
||||
|
||||
nonce = get_random_string(32)
|
||||
request.session['cross_domain_customer_auth_nonce'] = nonce
|
||||
query = {
|
||||
"next": request.POST.get("next", ""),
|
||||
"request_cross_domain_customer_auth_nonce": nonce,
|
||||
"request_cross_domain_customer_auth": "true",
|
||||
}
|
||||
return redirect_to_url(
|
||||
eventreverse_absolute(self.request.organizer, "presale:organizer.customer.login") + "?" + urlencode(query)
|
||||
)
|
||||
@@ -235,6 +235,11 @@ class AuthorizeView(View):
|
||||
if response_type not in RESPONSE_TYPES_SUPPORTED:
|
||||
return self._final_error("unsupported_response_type", "response_type unsupported")
|
||||
|
||||
if client.authorization_grant_type == "authorization-code" and response_type != "code":
|
||||
# with authorization_grant_type=implicit, response_type=code is still allowed, otherwise "hybrid flow" would be impossible
|
||||
return self._final_error("unsupported_response_type", "For clients with grant type set "
|
||||
"to authorization code, using implicit or hybrid flows is not allowed")
|
||||
|
||||
if response_type != "code" and response_mode == "query":
|
||||
return self._final_error("invalid_request", "response_mode query must not be used with implicit or hybrid flow")
|
||||
elif not response_mode:
|
||||
|
||||
@@ -42,7 +42,7 @@ import os
|
||||
import re
|
||||
from collections import Counter, OrderedDict, defaultdict
|
||||
from decimal import Decimal
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
@@ -55,6 +55,7 @@ from django.http import (
|
||||
FileResponse, Http404, HttpResponseRedirect, JsonResponse,
|
||||
)
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.utils.crypto import get_random_string
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.timezone import now
|
||||
@@ -117,8 +118,14 @@ class OrderDetailMixin(NoSearchIndexViewMixin):
|
||||
login_url = eventreverse(self.request.organizer, 'presale:organizer.customer.login', kwargs={})
|
||||
|
||||
if hasattr(self.request, "event_domain") and self.request.event_domain:
|
||||
next_url = quote(self.request.scheme + "://" + self.request.get_host() + self.request.get_full_path())
|
||||
return redirect_to_url(f'{login_url}?next={next_url}&request_cross_domain_customer_auth=true')
|
||||
nonce = get_random_string(32)
|
||||
self.request.session['cross_domain_customer_auth_nonce'] = nonce
|
||||
query = {
|
||||
"next": self.request.scheme + "://" + self.request.get_host() + self.request.get_full_path(),
|
||||
"request_cross_domain_customer_auth_nonce": nonce,
|
||||
"request_cross_domain_customer_auth": "true",
|
||||
}
|
||||
return redirect_to_url(f'{login_url}?{urlencode(query)}')
|
||||
|
||||
else:
|
||||
next_url = quote(self.request.get_full_path())
|
||||
@@ -366,7 +373,7 @@ class OrderDetails(EventViewMixin, OrderDetailMixin, CartMixin, TicketPageMixin,
|
||||
ctx['user_cancel_allowed'] = self.order.user_cancel_allowed
|
||||
for r in ctx['refunds']:
|
||||
if r.provider == 'giftcard':
|
||||
gc = GiftCard.objects.get(pk=r.info_data.get('gift_card'))
|
||||
gc = self.request.organizer.accepted_gift_cards.get(pk=r.info_data.get('gift_card'))
|
||||
r.giftcard = gc
|
||||
|
||||
return ctx
|
||||
|
||||
@@ -221,6 +221,11 @@ footer nav .btn-link {
|
||||
/*border-bottom: 2px solid $brand-primary;*/
|
||||
font-weight: bold;
|
||||
}
|
||||
.btn-link {
|
||||
padding: 0;
|
||||
margin-left: 5px;
|
||||
vertical-align: top;
|
||||
}
|
||||
img {
|
||||
vertical-align: baseline;
|
||||
}
|
||||
@@ -653,6 +658,35 @@ h2 .label {
|
||||
}
|
||||
|
||||
|
||||
.helper-position-relative {
|
||||
position: relative;
|
||||
}
|
||||
.helper-display-block {
|
||||
display: block !important;
|
||||
}
|
||||
.helper-display-inline {
|
||||
display: inline !important;
|
||||
}
|
||||
.helper-display-inline-block {
|
||||
display: inline-block !important;
|
||||
}
|
||||
.helper-display-none-soft {
|
||||
display: none;
|
||||
}
|
||||
.helper-display-none {
|
||||
display: none !important;
|
||||
}
|
||||
.helper-width-auto {
|
||||
width: auto;
|
||||
}
|
||||
.helper-width-100 {
|
||||
width: 100%;
|
||||
}
|
||||
.helper-space-below {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
|
||||
@import "_iframe.scss";
|
||||
@import "_a11y.scss";
|
||||
@import "_print.scss";
|
||||
|
||||
@@ -70,14 +70,27 @@ def admin_user(admin_team):
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def application():
|
||||
def app_developer():
|
||||
return User.objects.create_user('app-developer@example.org', 'app-developer')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client2():
|
||||
# We need a second test client instance to log in as the app developer user
|
||||
from django.test import Client
|
||||
return Client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def application(app_developer):
|
||||
secret = get_random_string(32)
|
||||
a = OAuthApplication.objects.create(
|
||||
name="pretalx",
|
||||
redirect_uris="https://pretalx.com",
|
||||
client_type='confidential',
|
||||
client_secret=secret,
|
||||
authorization_grant_type='authorization-code'
|
||||
authorization_grant_type='authorization-code',
|
||||
user=app_developer,
|
||||
)
|
||||
a._cached_secret = secret
|
||||
a.save()
|
||||
@@ -703,6 +716,47 @@ def test_token_revoke_access_token(client, admin_user, organizer, application: O
|
||||
assert list(grant.organizers.all()) == [organizer]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_token_app_disabled(client, client2, admin_user, organizer, application: OAuthApplication, app_developer):
|
||||
client.login(email='dummy@dummy.dummy', password='dummy')
|
||||
session = client.session
|
||||
session['pretix_auth_login_time'] = int(time.time())
|
||||
session.save()
|
||||
resp = client.get('/api/v1/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code' % (
|
||||
application.client_id, quote(application.redirect_uris)
|
||||
))
|
||||
assert resp.status_code == 200
|
||||
resp = client.post('/api/v1/oauth/authorize', data={
|
||||
'organizers': str(organizer.pk),
|
||||
'redirect_uri': application.redirect_uris,
|
||||
'scope': 'read write',
|
||||
'client_id': application.client_id,
|
||||
'response_type': 'code',
|
||||
'allow': 'Authorize',
|
||||
})
|
||||
assert resp.status_code == 302
|
||||
assert resp['Location'].startswith('https://pretalx.com?code=')
|
||||
code = resp['Location'].split("=")[1]
|
||||
client.logout()
|
||||
resp = client.post('/api/v1/oauth/token', data={
|
||||
'code': code,
|
||||
'redirect_uri': application.redirect_uris,
|
||||
'grant_type': 'authorization_code',
|
||||
}, HTTP_AUTHORIZATION='Basic ' + base64.b64encode(
|
||||
('%s:%s' % (application.client_id, application._cached_secret)).encode()).decode())
|
||||
assert resp.status_code == 200
|
||||
data = json.loads(resp.content.decode())
|
||||
access_token = data['access_token']
|
||||
resp = client.get('/api/v1/organizers/dummy/events/', HTTP_AUTHORIZATION='Bearer %s' % access_token)
|
||||
assert resp.status_code == 200
|
||||
|
||||
client2.login(email='app-developer@example.org', password='app-developer')
|
||||
client2.post(f'/control/settings/oauth/apps/{application.pk}/disable', {})
|
||||
|
||||
resp = client.get('/api/v1/organizers/dummy/events/', HTTP_AUTHORIZATION='Bearer %s' % access_token)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_user_revoke(client, admin_user, organizer, application: OAuthApplication):
|
||||
client.login(email='dummy@dummy.dummy', password='dummy')
|
||||
|
||||
@@ -35,7 +35,9 @@ from tests.plugins.stripe.test_checkout import apple_domain_create
|
||||
from tests.plugins.stripe.test_provider import MockedCharge
|
||||
|
||||
from pretix.base.models import InvoiceAddress, Order, OrderPosition, Team
|
||||
from pretix.base.models.giftcards import GiftCard
|
||||
from pretix.base.models.orders import OrderFee, OrderPayment, OrderRefund
|
||||
from pretix.base.models.organizer import Organizer
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -780,6 +782,28 @@ def test_payment_create_pending(token_client, organizer, event, order):
|
||||
assert order.status == Order.STATUS_PENDING
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_payment_create_giftcard(token_client, organizer, event, order):
|
||||
djmail.outbox = []
|
||||
with scopes_disabled():
|
||||
p_before = order.payments.count()
|
||||
resp = token_client.post('/api/v1/organizers/{}/events/{}/orders/{}/payments/'.format(
|
||||
organizer.slug, event.slug, order.code
|
||||
), format='json', data={
|
||||
'provider': 'giftcard',
|
||||
'state': 'confirmed',
|
||||
'amount': order.total,
|
||||
'info': {
|
||||
'foo': 'bar'
|
||||
}
|
||||
})
|
||||
assert resp.status_code == 400
|
||||
order.refresh_from_db()
|
||||
with scopes_disabled():
|
||||
assert order.payments.count() == p_before
|
||||
assert order.status == Order.STATUS_PENDING
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_payment_confirm(token_client, organizer, event, order):
|
||||
resp = token_client.post('/api/v1/organizers/{}/events/{}/orders/{}/payments/2/confirm/'.format(
|
||||
@@ -873,6 +897,24 @@ def test_payment_refund_fail(token_client, organizer, event, order, monkeypatch)
|
||||
assert resp.status_code == 400
|
||||
assert resp.data == {'detail': 'Invalid state of payment.'}
|
||||
|
||||
with scopes_disabled():
|
||||
o2 = Organizer.objects.create(name='Dummy 2', slug='dummy2', plugins='pretix.plugins.banktransfer')
|
||||
gc = GiftCard.objects.create(issuer=o2, currency='EUR')
|
||||
p1 = order.payments.create(
|
||||
provider='giftcard',
|
||||
state='confirmed',
|
||||
amount=Decimal('23.00'),
|
||||
payment_date=order.datetime,
|
||||
info=json.dumps({"gift_card": gc.pk})
|
||||
)
|
||||
resp = token_client.post('/api/v1/organizers/{}/events/{}/orders/{}/payments/{}/refund/'.format(
|
||||
organizer.slug, event.slug, order.code, p1.pk
|
||||
), format='json', data={})
|
||||
assert resp.status_code == 400
|
||||
assert resp.data == {'detail': 'External error: Gift card not found.'}
|
||||
p1.refresh_from_db()
|
||||
assert p1.state == OrderPayment.PAYMENT_STATE_CONFIRMED
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_payment_refund_success(token_client, organizer, event, order, monkeypatch):
|
||||
@@ -916,6 +958,22 @@ def test_payment_refund_success(token_client, organizer, event, order, monkeypat
|
||||
assert r.source == OrderRefund.REFUND_SOURCE_ADMIN
|
||||
assert r.comment == "Foo"
|
||||
|
||||
with scopes_disabled():
|
||||
gc = GiftCard.objects.create(issuer=organizer, currency='EUR')
|
||||
p1 = order.payments.create(
|
||||
provider='giftcard',
|
||||
state='confirmed',
|
||||
amount=Decimal('23.00'),
|
||||
payment_date=order.datetime,
|
||||
info=json.dumps({"gift_card": gc.pk})
|
||||
)
|
||||
resp = token_client.post('/api/v1/organizers/{}/events/{}/orders/{}/payments/{}/refund/'.format(
|
||||
organizer.slug, event.slug, order.code, p1.pk
|
||||
), format='json', data={})
|
||||
assert resp.status_code == 200
|
||||
p1.refresh_from_db()
|
||||
assert p1.state == OrderPayment.PAYMENT_STATE_REFUNDED
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_payment_refund_unavailable(token_client, organizer, event, order, monkeypatch):
|
||||
@@ -1935,6 +1993,42 @@ def test_refund_create_invalid_payment(token_client, organizer, event, order):
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_refund_create_giftcard(token_client, organizer, event, order):
|
||||
with scopes_disabled():
|
||||
o2 = Organizer.objects.create(name='Dummy 2', slug='dummy2', plugins='pretix.plugins.banktransfer')
|
||||
gc = GiftCard.objects.create(issuer=o2, currency='EUR')
|
||||
p1 = order.payments.create(
|
||||
provider='giftcard',
|
||||
state='confirmed',
|
||||
amount=Decimal('23.00'),
|
||||
payment_date=order.datetime,
|
||||
info=json.dumps({"gift_card": gc.pk})
|
||||
)
|
||||
with scopes_disabled():
|
||||
r_before = order.refunds.count()
|
||||
|
||||
resp = token_client.post(
|
||||
'/api/v1/organizers/{}/events/{}/orders/{}/refunds/'.format(
|
||||
organizer.slug, event.slug, order.code
|
||||
), format='json', data={
|
||||
"state": "created",
|
||||
"provider": "giftcard",
|
||||
"amount": "23.00",
|
||||
"source": "admin",
|
||||
"payment": p1.pk,
|
||||
"info": {
|
||||
"gift_card": gc.pk,
|
||||
}
|
||||
}
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
with scopes_disabled():
|
||||
assert order.refunds.count() == r_before
|
||||
order.refresh_from_db()
|
||||
assert order.status == Order.STATUS_PENDING
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_order_delete(token_client, organizer, event, order):
|
||||
resp = token_client.delete(
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#
|
||||
# This file is part of pretix (Community Edition).
|
||||
#
|
||||
# Copyright (C) 2014-2020 Raphael Michel and contributors
|
||||
# Copyright (C) 2020-today pretix GmbH and contributors
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
|
||||
# Public License as published by the Free Software Foundation in version 3 of the License.
|
||||
#
|
||||
# ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are
|
||||
# applicable granting you additional permissions and placing additional restrictions on your usage of this software.
|
||||
# Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive
|
||||
# this file, see <https://pretix.eu/about/en/license>.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
|
||||
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
|
||||
# details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_allowed_json():
|
||||
assert json.loads('{"float":1.5,"int":161,"arr":[]}') == {"float": 1.5, "int": 161, "arr": []}
|
||||
|
||||
|
||||
def test_disallowed_json_float_consts():
|
||||
with pytest.raises(KeyError):
|
||||
json.loads("Infinity")
|
||||
with pytest.raises(KeyError):
|
||||
json.loads("-Infinity")
|
||||
with pytest.raises(KeyError):
|
||||
json.loads("NaN")
|
||||
with pytest.raises(KeyError):
|
||||
json.loads("[123, NaN, Infinity, -Infinity]")
|
||||
@@ -5959,3 +5959,14 @@ class CustomerCheckoutTestCase(BaseCheckoutTestCase, TestCase):
|
||||
response = self.client.get('/%s/%s/checkout/payment/' % (self.orga.slug, self.event.slug), follow=True)
|
||||
assert 'Gift card' in response.content.decode()
|
||||
assert '(1 available)' in response.content.decode()
|
||||
|
||||
def test_validation_bypass_error_async_id_is_fixed(self):
|
||||
with scopes_disabled():
|
||||
CartPosition.objects.create(
|
||||
event=self.event, cart_id=self.session_key, item=self.ticket,
|
||||
price=0, listed_price=0, price_after_voucher=0, expires=now() + timedelta(minutes=10)
|
||||
)
|
||||
|
||||
response = self.client.post('/%s/%s/checkout/confirm/?async_id=1' % (self.orga.slug, self.event.slug), follow=False)
|
||||
self.assertRedirects(response, '/%s/%s/checkout/customer/' % (self.orga.slug, self.event.slug),
|
||||
target_status_code=200)
|
||||
@@ -721,9 +721,21 @@ def _cross_domain_login(env, client, client2, org_alt=False):
|
||||
else:
|
||||
KnownDomain.objects.create(domainname='event.test', organizer=env[0], event=env[1])
|
||||
|
||||
# Log in on org domain
|
||||
# Start session on event domain
|
||||
path = '/conf/' if org_alt else '/'
|
||||
r = client.post(f'/account/login?next=https://event.test{path}redeem&request_cross_domain_customer_auth=true', {
|
||||
r = client2.post(f'{path}account/loginstart', {
|
||||
'next': f'https://event.test{path}redeem',
|
||||
}, HTTP_HOST='event.test')
|
||||
assert r.status_code == 302
|
||||
u = urlparse(r.headers['Location'])
|
||||
assert u.netloc == 'org.test'
|
||||
assert u.path == '/account/login'
|
||||
assert 'request_cross_domain_customer_auth=' in u.query
|
||||
assert 'request_cross_domain_customer_auth_nonce=' in u.query
|
||||
assert 'next=' in u.query
|
||||
|
||||
# Log in on org domain
|
||||
r = client.post(f'{u.path}?{u.query}', {
|
||||
'email': 'john@example.org',
|
||||
'password': 'foo',
|
||||
}, HTTP_HOST='org.test')
|
||||
@@ -734,6 +746,7 @@ def _cross_domain_login(env, client, client2, org_alt=False):
|
||||
assert u.path == path + 'redeem'
|
||||
q = parse_qs(u.query)
|
||||
assert 'cross_domain_customer_auth' in q
|
||||
assert 'cross_domain_customer_auth_nonce' in q
|
||||
|
||||
# Take session over to event domain
|
||||
r = client2.get(f'{path}?{u.query}', HTTP_HOST='event.test')
|
||||
@@ -745,7 +758,7 @@ def _cross_domain_login(env, client, client2, org_alt=False):
|
||||
def test_cross_domain_login(env, client, client2):
|
||||
_cross_domain_login(env, client, client2)
|
||||
|
||||
# Logged in on evnet domain
|
||||
# Logged in on event domain
|
||||
r = client.get('/', HTTP_HOST='event.test')
|
||||
assert r.status_code == 200
|
||||
assert b'john@example.org' in r.content
|
||||
@@ -896,7 +909,14 @@ def test_cross_domain_login_with_sso(env, client, client2, provider):
|
||||
},
|
||||
)
|
||||
|
||||
url = f'/account/login/{provider.pk}/?next=https://event.test/redeem&request_cross_domain_customer_auth=true'
|
||||
r = client2.post('/account/loginstart', {"next": "https://event.test/redeem"}, follow=False, HTTP_HOST='event.test')
|
||||
assert r.status_code == 302
|
||||
assert "/account/login" in r['Location']
|
||||
|
||||
u = urlparse(r.headers['Location'])
|
||||
nonce = parse_qs(u.query)['request_cross_domain_customer_auth_nonce'][0]
|
||||
url = (f'/account/login/{provider.pk}/?next=https://event.test/redeem&request_cross_domain_customer_auth=true&'
|
||||
f'request_cross_domain_customer_auth_nonce={nonce}')
|
||||
r = client.get(url, follow=False, HTTP_HOST='org.test')
|
||||
assert r.status_code == 302
|
||||
assert "/authorize" in r['Location']
|
||||
@@ -910,6 +930,7 @@ def test_cross_domain_login_with_sso(env, client, client2, provider):
|
||||
assert u.path == '/redeem'
|
||||
q = parse_qs(u.query)
|
||||
assert 'cross_domain_customer_auth' in q
|
||||
assert 'cross_domain_customer_auth_nonce' in q
|
||||
|
||||
# Take session over to event domain
|
||||
r = client2.get(f'/?{u.query}', HTTP_HOST='event.test')
|
||||
|
||||
@@ -72,6 +72,9 @@ def ssoclient(env, client):
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_authorize_final_errors(env, client, ssoclient):
|
||||
ssoclient[0].authorization_grant_type = "implicit"
|
||||
ssoclient[0].save()
|
||||
|
||||
r = client.get('/bigevents/oauth2/v1/authorize')
|
||||
assert r.status_code == 400
|
||||
assert b'client_id missing' in r.content
|
||||
@@ -111,6 +114,9 @@ def test_authorize_final_errors(env, client, ssoclient):
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_authorize_basic_redirect_errors(env, client, ssoclient):
|
||||
ssoclient[0].authorization_grant_type = "implicit"
|
||||
ssoclient[0].save()
|
||||
|
||||
r = client.get(
|
||||
f'/bigevents/oauth2/v1/authorize?client_id={ssoclient[0].client_id}&redirect_uri=https://example.net&response_type=code')
|
||||
assert r.status_code == 302
|
||||
@@ -494,8 +500,29 @@ def test_token_client_secret_post(env, client, ssoclient):
|
||||
assert 86390 < d['expires_in'] <= 86400
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_authorize_implicit_flow_not_allowed_for_authcode_client(env, client, ssoclient):
|
||||
r = client.post('/bigevents/account/login', {
|
||||
'email': 'john@example.org',
|
||||
'password': 'foo',
|
||||
})
|
||||
assert r.status_code == 302
|
||||
|
||||
url = f'/bigevents/oauth2/v1/authorize?client_id={ssoclient[0].client_id}&' \
|
||||
f'redirect_uri=https://example.net&' \
|
||||
f'response_type=id_token&' \
|
||||
f'state=STATE&' \
|
||||
f'nonce=NONCE123&' \
|
||||
f'scope=openid+profile+email'
|
||||
r = client.get(url)
|
||||
assert r.status_code == 400
|
||||
assert b'clients with grant type set to authorization code' in r.content
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_authorize_implicit_flow(env, client, ssoclient):
|
||||
ssoclient[0].authorization_grant_type = "implicit"
|
||||
ssoclient[0].save()
|
||||
r = client.post('/bigevents/account/login', {
|
||||
'email': 'john@example.org',
|
||||
'password': 'foo',
|
||||
@@ -544,6 +571,8 @@ def test_authorize_implicit_flow(env, client, ssoclient):
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_authorize_hybrid_flow(env, client, ssoclient):
|
||||
ssoclient[0].authorization_grant_type = "implicit"
|
||||
ssoclient[0].save()
|
||||
r = client.post('/bigevents/account/login', {
|
||||
'email': 'john@example.org',
|
||||
'password': 'foo',
|
||||
|
||||
Reference in new issue
Block a user