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:
Jens Langhammer 2023-02-19 17:31:20 +01:00
parent 0874574e5c
commit 1ac2e924a2
No known key found for this signature in database
2 changed files with 22 additions and 2 deletions

View file

@ -31,8 +31,14 @@ class TokenSerializer(ManagedSerializer, ModelSerializer):
def validate(self, attrs: dict[Any, str]) -> dict[Any, str]: def validate(self, attrs: dict[Any, str]) -> dict[Any, str]:
"""Ensure only API or App password tokens are created.""" """Ensure only API or App password tokens are created."""
request: Request = self.context["request"] request: Request = self.context.get("request")
attrs.setdefault("user", request.user) 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) attrs.setdefault("intent", TokenIntents.INTENT_API)
if attrs.get("intent") not in [TokenIntents.INTENT_API, TokenIntents.INTENT_APP_PASSWORD]: if attrs.get("intent") not in [TokenIntents.INTENT_API, TokenIntents.INTENT_APP_PASSWORD]:
raise ValidationError(f"Invalid intent {attrs.get('intent')}") raise ValidationError(f"Invalid intent {attrs.get('intent')}")

View file

@ -5,6 +5,7 @@ from django.urls.base import reverse
from guardian.shortcuts import get_anonymous_user from guardian.shortcuts import get_anonymous_user
from rest_framework.test import APITestCase 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.models import USER_ATTRIBUTE_TOKEN_EXPIRING, Token, TokenIntents, User
from authentik.core.tests.utils import create_test_admin_user from authentik.core.tests.utils import create_test_admin_user
from authentik.lib.generators import generate_id from authentik.lib.generators import generate_id
@ -99,3 +100,16 @@ class TestTokenAPI(APITestCase):
self.assertEqual(len(body["results"]), 2) self.assertEqual(len(body["results"]), 2)
self.assertEqual(body["results"][0]["identifier"], token_should.identifier) self.assertEqual(body["results"][0]["identifier"], token_should.identifier)
self.assertEqual(body["results"][1]["identifier"], token_should_not.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)
)