outposts: fix integrity error with tokens

Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
This commit is contained in:
Jens Langhammer 2021-06-13 13:36:54 +02:00
parent ddfc943bba
commit fc8004db2b
2 changed files with 17 additions and 15 deletions

View File

@ -18,7 +18,6 @@ class AuthentikAPIConfig(AppConfig):
# Class is defined here as it needs to be created early enough that drf-spectacular will
# find it, but also won't cause any import issues
# pylint: disable=unused-variable
class TokenSchema(OpenApiAuthenticationExtension):
"""Auth schema"""

View File

@ -8,7 +8,7 @@ from uuid import uuid4
from dacite import from_dict
from django.contrib.auth.models import Permission
from django.core.cache import cache
from django.db import models, transaction
from django.db import IntegrityError, models, transaction
from django.db.models.base import Model
from django.utils.translation import gettext_lazy as _
from docker.client import DockerClient
@ -380,13 +380,11 @@ class Outpost(models.Model):
tokens = Token.filter_not_expired(
identifier=self.token_identifier,
intent=TokenIntents.INTENT_API,
managed=managed,
)
if tokens.exists():
token = tokens.first()
if not token.managed:
token.managed = managed
token.save()
return token
return tokens.first()
try:
return Token.objects.create(
user=self.user,
identifier=self.token_identifier,
@ -395,6 +393,11 @@ class Outpost(models.Model):
expiring=False,
managed=managed,
)
except IntegrityError:
# Integrity error happens mostly when managed is re-used
Token.objects.filter(managed=managed).delete()
Token.objects.filter(identifier=self.token_identifier).delete()
return self.token
def get_required_objects(self) -> Iterable[Union[models.Model, str]]:
"""Get an iterator of all objects the user needs read access to"""