flows: fix invalid background URL when using manually set static or http

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-06-02 21:04:03 +02:00
parent a113778ca7
commit 2f64b76eba
3 changed files with 16 additions and 13 deletions

View file

@ -1,6 +1,5 @@
"""Flow API Views"""
from dataclasses import dataclass
from typing import Optional
from django.core.cache import cache
from django.db.models import Model
@ -11,7 +10,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
from guardian.shortcuts import get_objects_for_user
from rest_framework.decorators import action
from rest_framework.fields import FileField
from rest_framework.fields import FileField, ReadOnlyField
from rest_framework.parsers import MultiPartParser
from rest_framework.request import Request
from rest_framework.response import Response
@ -43,15 +42,7 @@ class FlowSerializer(ModelSerializer):
cache_count = SerializerMethodField()
background = SerializerMethodField()
def get_background(self, instance: Flow) -> Optional[str]:
"""When background was set to a URL, return the name as-is"""
if not instance.background:
return None
if instance.background.name.startswith("http"):
return instance.background.name
return instance.background.url
background = ReadOnlyField(source="background_url")
def get_cache_count(self, flow: Flow) -> int:
"""Get count of cached flows"""
@ -324,7 +315,7 @@ class FlowViewSet(ModelViewSet):
url = request.data.get("url", None)
if not url:
return HttpResponseBadRequest()
flow.background = url
flow.background.name = url
flow.save()
return Response({})

View file

@ -115,6 +115,18 @@ class Flow(SerializerModel, PolicyBindingModel):
help_text=_("Background shown during execution"),
)
@property
def background_url(self) -> Optional[str]:
"""Get the URL to the background image. If the name is /static or starts with http
it is returned as-is"""
if not self.background:
return None
if self.background.name.startswith("http") or self.background.name.startswith(
"/static"
):
return self.background.name
return self.background.url
stages = models.ManyToManyField(Stage, through="FlowStageBinding", blank=True)
@property

View file

@ -96,7 +96,7 @@ class ChallengeStageView(StageView):
if "title" not in challenge.initial_data:
challenge.initial_data["title"] = self.executor.flow.title
if "background" not in challenge.initial_data:
challenge.initial_data["background"] = self.executor.flow.background.url
challenge.initial_data["background"] = self.executor.flow.background_url
if isinstance(challenge, WithUserInfoChallenge):
# If there's a pending user, update the `username` field
# this field is only used by password managers.