florimondmanca/djangorestframework-api-key

APIKey generation in `CreateView` on a per-User basis?

Closed this issue · 0 comments

I would like to allow users to generate their own APIs for each user with this wonderful library.
However, I do not know what to do because I cannot register a hash or prefix in the first place.

model.py

from django.db import models
from rest_framework_api_key.models import AbstractAPIKey
from rest_framework_api_key.models import BaseAPIKeyManager
from rest_framework_api_key.crypto import KeyGenerator

class UserAPIKeyManager(BaseAPIKeyManager):
    key_generator = KeyGenerator(prefix_length=8, secret_key_length=32)

class UserAPIKey(AbstractAPIKey):
    key = UserAPIKeyManager()
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="api_keys")
    description = models.TextField(max_length=1000, blank=True)

    class Meta:
        verbose_name = "API Key"
        verbose_name_plural = "API Keys"

form.py

class UserAPIKeyCreateForm(ModelForm):
    """APIキー作成用フォーム"""

    class Meta:
        model = UserAPIKey
        fields = "__all__"
        exclude = ('user',)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

view.py

class UserAPIKeyCreate(LoginRequiredMixin, generic.CreateView):
    
    template_name = 'account/registration/api_key_create.html'
    model = UserAPIKey
    form_class = UserAPIKeyCreateForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        form.instance.created = localtime(timezone.now())
        return super().form_valid(form)
    
    def get_success_url(self):
        return reverse_lazy('account:api_list')