lib: fix uploaded files not being saved correctly, add tests

closes #4110 #4109 #4107

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2022-11-30 12:48:33 +02:00
parent 8a926aaa73
commit d5329432fe
2 changed files with 33 additions and 6 deletions

View File

@ -1,6 +1,8 @@
"""Test Applications API""" """Test Applications API"""
from json import loads 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 django.urls import reverse
from rest_framework.test import APITestCase from rest_framework.test import APITestCase
@ -21,7 +23,7 @@ class TestApplicationsAPI(APITestCase):
redirect_uris="http://some-other-domain", redirect_uris="http://some-other-domain",
authorization_flow=create_test_flow(), authorization_flow=create_test_flow(),
) )
self.allowed = Application.objects.create( self.allowed: Application = Application.objects.create(
name="allowed", name="allowed",
slug="allowed", slug="allowed",
meta_launch_url="https://goauthentik.io/%(username)s", meta_launch_url="https://goauthentik.io/%(username)s",
@ -35,6 +37,31 @@ class TestApplicationsAPI(APITestCase):
order=0, 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): def test_check_access(self):
"""Test check_access operation""" """Test check_access operation"""
self.client.force_login(self.user) self.client.force_login(self.user)

View File

@ -24,17 +24,17 @@ class FilePathSerializer(PassiveSerializer):
url = CharField() url = CharField()
def set_file(request: Request, obj: Model, field: str): def set_file(request: Request, obj: Model, field_name: str):
"""Upload file""" """Upload file"""
field = getattr(obj, field) field = getattr(obj, field_name)
icon = request.FILES.get("file", None) file = request.FILES.get("file", None)
clear = request.data.get("clear", "false").lower() == "true" clear = request.data.get("clear", "false").lower() == "true"
if clear: if clear:
# .delete() saves the model by default # .delete() saves the model by default
field.delete() field.delete()
return Response({}) return Response({})
if icon: if file:
field = icon setattr(obj, field_name, file)
try: try:
obj.save() obj.save()
except PermissionError as exc: except PermissionError as exc: