florimondmanca / djangorestframework-api-key

🔐 API key permissions for Django REST Framework
https://florimondmanca.github.io/djangorestframework-api-key/
MIT License
678 stars 104 forks source link

IntegrityError using AbstractAPIKey #237

Closed theshajha closed 1 year ago

theshajha commented 1 year ago

Describe the bug I am extending the model to include what organisation this API key is for. My platform offers creation of multiple orgs by the same user. So I wish to ensure they generate api keys specific to each org only. I extended the AbstractAPIKey model like this -

class UserAPIKey(AbstractAPIKey):
    user = models.ForeignKey(Users, on_delete=models.CASCADE)
    organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=128, blank=True, null=True)

    def __str__(self):
        return f"{self.user.first_name} - {self.name}"

But now when I go to create new API Keys using this model -

# Check if the user already has an API key
        existing_key = UserAPIKey.objects.filter(user=user, organisation_id=org_id).first()

        if existing_key:
            # Revoke and delete the existing key
            existing_key.is_active = False
            existing_key.save()
            existing_key.delete()

        # Create a unique key name by slugifying the username and adding a random alphanumeric string
        key_name = f"{slugify(organisation.slug)}-{secrets.token_hex(10)}"

        # Create a new API key for the user
        api_key, plain_key = APIKey.objects.create_key(name=key_name)

        try:
            new_key = UserAPIKey.objects.create(
                name=key_name,
                user=user,
                organisation=organisation,
                hashed_key=api_key.hashed_key
            )
        except IntegrityError:
            pass

I get IntegrityError - duplicate key value violates unique constraint "users_userapikey_pkey" DETAIL: Key (id)=() already exists.

What am I missing here? 🤔