core: fix error when creating token without request in context
closes #4716 Signed-off-by: Jens Langhammer <jens@goauthentik.io>
This commit is contained in:
parent
0874574e5c
commit
1ac2e924a2
|
@ -31,8 +31,14 @@ class TokenSerializer(ManagedSerializer, ModelSerializer):
|
|||
|
||||
def validate(self, attrs: dict[Any, str]) -> dict[Any, str]:
|
||||
"""Ensure only API or App password tokens are created."""
|
||||
request: Request = self.context["request"]
|
||||
attrs.setdefault("user", request.user)
|
||||
request: Request = self.context.get("request")
|
||||
if not request:
|
||||
if "user" not in attrs:
|
||||
raise ValidationError("Missing user")
|
||||
if "intent" not in attrs:
|
||||
raise ValidationError("Missing intent")
|
||||
else:
|
||||
attrs.setdefault("user", request.user)
|
||||
attrs.setdefault("intent", TokenIntents.INTENT_API)
|
||||
if attrs.get("intent") not in [TokenIntents.INTENT_API, TokenIntents.INTENT_APP_PASSWORD]:
|
||||
raise ValidationError(f"Invalid intent {attrs.get('intent')}")
|
||||
|
|
|
@ -5,6 +5,7 @@ from django.urls.base import reverse
|
|||
from guardian.shortcuts import get_anonymous_user
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
from authentik.core.api.tokens import TokenSerializer
|
||||
from authentik.core.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents, User
|
||||
from authentik.core.tests.utils import create_test_admin_user
|
||||
from authentik.lib.generators import generate_id
|
||||
|
@ -99,3 +100,16 @@ class TestTokenAPI(APITestCase):
|
|||
self.assertEqual(len(body["results"]), 2)
|
||||
self.assertEqual(body["results"][0]["identifier"], token_should.identifier)
|
||||
self.assertEqual(body["results"][1]["identifier"], token_should_not.identifier)
|
||||
|
||||
def test_serializer_no_request(self):
|
||||
"""Test serializer without request"""
|
||||
self.assertTrue(
|
||||
TokenSerializer(
|
||||
data={
|
||||
"identifier": generate_id(),
|
||||
"intent": TokenIntents.INTENT_APP_PASSWORD,
|
||||
"key": generate_id(),
|
||||
"user": self.user.pk,
|
||||
}
|
||||
).is_valid(raise_exception=True)
|
||||
)
|
||||
|
|
Reference in New Issue