jazzband / django-rest-knox

Authentication Module for django rest auth
MIT License
1.17k stars 213 forks source link

Better automated schema generation? #310

Closed giovannicimolin closed 1 year ago

giovannicimolin commented 1 year ago

I've recently started using this with drf-spetacular and had to describe some of the API using extensions. I'll evaluate if it's possible to modify this library in a way that the schema is automatically generated without needing any overrides.

Ping me if you want to take a stab at this! I can review/merge.

If anyone is also trying to use this with drf-spetacular and code generators, this is what I'm using now:

from drf_spectacular.extensions import (
    OpenApiAuthenticationExtension,
    OpenApiViewExtension,
)
from rest_framework import serializers

class KnoxAuthentication(OpenApiAuthenticationExtension):
    """
    Knox authentication Open API definition.
    """

    target_class = "knox.auth.TokenAuthentication"
    name = "TokenAuthentication"

    def get_security_definition(self, auto_schema):
        """
        Custom definition for APIView.
        """
        return {
            "type": "apiKey",
            "in": "header",
            "name": "Authorization",
        }

class LogoutResponseSerializer(serializers.Serializer):
    """
    Empty logout response serializer
    """

class FixLogoutView(OpenApiViewExtension):
    target_class = "knox.views.LogoutView"

    def view_replacement(self):
        """
        Fix view
        """

        class Fixed(self.target_class):
            serializer_class = LogoutResponseSerializer

        return Fixed

class FixLogoutAllView(OpenApiViewExtension):
    target_class = "knox.views.LogoutAllView"

    def view_replacement(self):
        """
        Fix view
        """

        class Fixed(self.target_class):
            serializer_class = LogoutResponseSerializer

        return Fixed

This doesn't yield a 1 to 1 to the API output response, but it doesn't matter for my usage.

Note: be mindful of the settings if you are re-using this, they are specific to my projects.

giovannicimolin commented 1 year ago

Just realized this is a duplicate of/related to: https://github.com/jazzband/django-rest-knox/issues/292.

I'll close this here and move my comment there.