From d5329432fed9ed2a025ca0f7f3aa0317b44cfa85 Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Wed, 30 Nov 2022 12:48:33 +0200 Subject: [PATCH] lib: fix uploaded files not being saved correctly, add tests closes #4110 #4109 #4107 Signed-off-by: Jens Langhammer --- authentik/core/tests/test_applications_api.py | 29 ++++++++++++++++++- authentik/lib/utils/file.py | 10 +++---- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/authentik/core/tests/test_applications_api.py b/authentik/core/tests/test_applications_api.py index 9eeaf3131..4b4326f67 100644 --- a/authentik/core/tests/test_applications_api.py +++ b/authentik/core/tests/test_applications_api.py @@ -1,6 +1,8 @@ """Test Applications API""" from json import loads +from django.core.files.base import ContentFile +from django.test.client import BOUNDARY, MULTIPART_CONTENT, encode_multipart from django.urls import reverse from rest_framework.test import APITestCase @@ -21,7 +23,7 @@ class TestApplicationsAPI(APITestCase): redirect_uris="http://some-other-domain", authorization_flow=create_test_flow(), ) - self.allowed = Application.objects.create( + self.allowed: Application = Application.objects.create( name="allowed", slug="allowed", meta_launch_url="https://goauthentik.io/%(username)s", @@ -35,6 +37,31 @@ class TestApplicationsAPI(APITestCase): order=0, ) + def test_set_icon(self): + """Test set_icon""" + file = ContentFile(b"text", "name") + self.client.force_login(self.user) + response = self.client.post( + reverse( + "authentik_api:application-set-icon", + kwargs={"slug": self.allowed.slug}, + ), + data=encode_multipart(data={"file": file}, boundary=BOUNDARY), + content_type=MULTIPART_CONTENT, + ) + self.assertEqual(response.status_code, 200) + + app_raw = self.client.get( + reverse( + "authentik_api:application-detail", + kwargs={"slug": self.allowed.slug}, + ), + ) + app = loads(app_raw.content) + self.allowed.refresh_from_db() + self.assertEqual(self.allowed.get_meta_icon, app["meta_icon"]) + self.assertEqual(self.allowed.meta_icon.read(), b"text") + def test_check_access(self): """Test check_access operation""" self.client.force_login(self.user) diff --git a/authentik/lib/utils/file.py b/authentik/lib/utils/file.py index 52e24212b..2dc1d8429 100644 --- a/authentik/lib/utils/file.py +++ b/authentik/lib/utils/file.py @@ -24,17 +24,17 @@ class FilePathSerializer(PassiveSerializer): url = CharField() -def set_file(request: Request, obj: Model, field: str): +def set_file(request: Request, obj: Model, field_name: str): """Upload file""" - field = getattr(obj, field) - icon = request.FILES.get("file", None) + field = getattr(obj, field_name) + file = request.FILES.get("file", None) clear = request.data.get("clear", "false").lower() == "true" if clear: # .delete() saves the model by default field.delete() return Response({}) - if icon: - field = icon + if file: + setattr(obj, field_name, file) try: obj.save() except PermissionError as exc: