Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: django-rest-framework #8053

Draft
wants to merge 28 commits into
base: feat/rpc-api
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
5186823
chore: add django-rest-framework/drf-spectacular
jennifer-richards Oct 11, 2024
283cf2b
chore: set up drf and auth/authz
jennifer-richards Oct 11, 2024
b664548
chore: spectacular setup
jennifer-richards Oct 11, 2024
622958c
chore: add drf-standardized-errors
jennifer-richards Oct 12, 2024
b42219b
refactor: rpc_person -> PersonViewSet
jennifer-richards Oct 12, 2024
0ad57d0
refactor: rpc_subject_person -> SubjectPersonView
jennifer-richards Oct 12, 2024
3e4bf37
refactor: rpc_persons -> RpcPersonsView
jennifer-richards Oct 15, 2024
73e14e2
refactor: rpc_draft -> DraftViewSet
jennifer-richards Oct 15, 2024
7c2733a
refactor: drafts_by_names -> DraftsByNameView
jennifer-richards Oct 15, 2024
11f8cc1
refactor: submitted_to_rpc -> DraftViewSet
jennifer-richards Oct 15, 2024
14c3bfe
refactor: rfc_original_stream -> RfcViewSet
jennifer-richards Oct 15, 2024
6d49bb8
refactor: create_demo_person -> DemoViewSet
jennifer-richards Oct 15, 2024
82e2b24
refactor: create_demo_draft -> DemoViewSet
jennifer-richards Oct 16, 2024
e327111
fix: instantiate AnonymousUser class
jennifer-richards Oct 16, 2024
29e0cfa
refactor: move RpcPersonView into PersonViewSet
jennifer-richards Oct 16, 2024
88c0917
fix: adjust URLs
jennifer-richards Oct 16, 2024
99e8fb0
chore: remove unused imports
jennifer-richards Oct 16, 2024
efa2d3d
style: Black
jennifer-richards Oct 16, 2024
9eb8cbe
chore: Remove unused code
jennifer-richards Oct 16, 2024
b002c19
refactor: use serializer for parsing
jennifer-richards Oct 16, 2024
c50977f
chore: drf-standardized-errors settings
jennifer-richards Oct 16, 2024
dd7f9fd
chore: adjust drf-spectacular settings
jennifer-richards Oct 16, 2024
28b1e04
chore: generated API schema for comparison
jennifer-richards Oct 16, 2024
8600744
refactor: serializers_rpc module
jennifer-richards Oct 16, 2024
2a0182f
style: unnecessary parentheses
jennifer-richards Oct 16, 2024
1f6f549
fix: bad subject ID is really a 404
jennifer-richards Oct 16, 2024
3eaffa6
chore: fix comment
jennifer-richards Oct 16, 2024
ac4c006
Merge branch 'feat/rpc-api' into rpc-api-drf
jennifer-richards Oct 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions ietf/api/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ def ready(self):
https://docs.djangoproject.com/en/4.2/ref/applications/#django.apps.AppConfig.ready
"""
populate_api_list()
# Import drf-spectacular extensions
import ietf.api.schema # noqa
19 changes: 19 additions & 0 deletions ietf/api/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright The IETF Trust 2024, All Rights Reserved
#
from rest_framework import authentication
from django.contrib.auth.models import AnonymousUser


class ApiKeyAuthentication(authentication.BaseAuthentication):
"""API-Key header authentication"""

def authenticate(self, request):
"""Extract the authentication token, if present

This does not validate the token, it just arranges for it to be available in request.auth.
It's up to a Permissions class to validate it for the appropriate endpoint.
"""
token = request.META.get("HTTP_X_API_KEY", None)
if token is None:
return None
return AnonymousUser(), token # available as request.user and request.auth
18 changes: 18 additions & 0 deletions ietf/api/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright The IETF Trust 2024, All Rights Reserved
#
import rest_framework.permissions
from ietf.api.ietf_utils import is_valid_token


class ApiKeyEndpointPermissions(rest_framework.permissions.BasePermission):
"""Permissions class that validates a token using is_valid_token

The view class must indicate the relevant endpoint by setting `api_key_endpoint`.
Must be used with an Authentication class that puts a token in request.auth.
"""
def has_permission(self, request, view):
endpoint = getattr(view, "api_key_endpoint", None)
auth_token = getattr(request, "auth", None)
if endpoint is not None and auth_token is not None:
return is_valid_token(endpoint, auth_token)
return False
20 changes: 20 additions & 0 deletions ietf/api/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Copyright The IETF Trust 2024, All Rights Reserved
#
from drf_spectacular.extensions import OpenApiAuthenticationExtension


class ApiKeyAuthenticationScheme(OpenApiAuthenticationExtension):
"""Authentication scheme extension for the ApiKeyAuthentication

Used by drf-spectacular when rendering the OpenAPI schema
"""
target_class = "ietf.api.authentication.ApiKeyAuthentication"
name = "apiKeyAuth"

def get_security_definition(self, auto_schema):
return {
"type": "apiKey",
"description": "Shared secret in the X-Api-Key header",
"name": "X-Api-Key",
"in": "header",
}
150 changes: 150 additions & 0 deletions ietf/api/serializers_rpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Copyright The IETF Trust 2024, All Rights Reserved
#
import datetime
from typing import Literal, Optional

from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers

from ietf.doc.models import DocumentAuthor, Document
from ietf.person.models import Person


class PersonBatchSerializer(serializers.Serializer):
person_ids = serializers.ListField(child=serializers.IntegerField())


class PersonSerializer(serializers.ModelSerializer):
"""Serializer for a Person in a response"""

plain_name = serializers.SerializerMethodField()

class Meta:
model = Person
fields = ["id", "plain_name"]

def get_plain_name(self, person) -> str:
return person.plain_name()


class DocumentAuthorSerializer(serializers.ModelSerializer):
"""Serializer for a DocumentAuthor in a response"""

plain_name = serializers.SerializerMethodField()

class Meta:
model = DocumentAuthor
fields = ["person", "plain_name"]

def get_plain_name(self, document_author: DocumentAuthor) -> str:
return document_author.person.plain_name()


class FullDraftSerializer(serializers.ModelSerializer):
source_format = serializers.SerializerMethodField()
authors = DocumentAuthorSerializer(many=True, source="documentauthor_set")
shepherd = serializers.SerializerMethodField()

class Meta:
model = Document
fields = [
"id",
"name",
"rev",
"stream",
"title",
"pages",
"source_format",
"authors",
"shepherd",
"intended_std_level",
]

def get_source_format(
self, doc: Document
) -> Literal["unknown", "xml-v2", "xml-v3", "txt"]:
submission = doc.submission()
if submission is None:
return "unknown"
if ".xml" in submission.file_types:
if submission.xml_version == "3":
return "xml-v3"
else:
return "xml-v2"
elif ".txt" in submission.file_types:
return "txt"
return "unknown"

@extend_schema_field(OpenApiTypes.EMAIL)
def get_shepherd(self, doc: Document) -> str:
if doc.shepherd:
return doc.shepherd.formatted_ascii_email()
return ""


class DraftSerializer(FullDraftSerializer):
class Meta:
model = Document
fields = [
"id",
"name",
"rev",
"stream",
"title",
"pages",
"source_format",
"authors",
]


class SubmittedToQueueSerializer(FullDraftSerializer):
submitted = serializers.SerializerMethodField()

class Meta:
model = Document
fields = [
"id",
"name",
"stream",
"submitted",
]

def get_submitted(self, doc) -> Optional[datetime.datetime]:
event = doc.sent_to_rfc_editor_event()
return None if event is None else event.time


class OriginalStreamSerializer(serializers.ModelSerializer):
stream = serializers.CharField(read_only=True, source="orig_stream_id")

class Meta:
model = Document
fields = ["rfc_number", "stream"]


class DemoPersonCreateSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)


class DemoPersonSerializer(serializers.ModelSerializer):
person_pk = serializers.IntegerField(source="pk")

class Meta:
model = Person
fields = ["user_id", "person_pk"]


class DemoDraftCreateSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255, required=True)
stream_id = serializers.CharField(default="ietf")
rev = serializers.CharField(default=None)
states = serializers.DictField(child=serializers.CharField(), default=None)


class DemoDraftSerializer(serializers.ModelSerializer):
doc_id = serializers.IntegerField(source="pk")

class Meta:
model = Document
fields = ["doc_id", "name"]
21 changes: 12 additions & 9 deletions ietf/api/urls_rpc.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
# Copyright The IETF Trust 2023-2024, All Rights Reserved

from rest_framework import routers
from django.urls import include, path

from ietf.api import views_rpc

from ietf.utils.urls import url

router = routers.DefaultRouter()
router.register(r"demo", views_rpc.DemoViewSet, basename="demo")
router.register(r"draft", views_rpc.DraftViewSet, basename="draft")
router.register(r"person", views_rpc.PersonViewSet)
router.register(r"rfc", views_rpc.RfcViewSet, basename="rfc")

urlpatterns = [
url(r"^doc/create_demo_draft/$", views_rpc.create_demo_draft),
url(r"^doc/drafts/(?P<doc_id>[0-9]+)$", views_rpc.rpc_draft),
url(r"^doc/drafts_by_names/", views_rpc.drafts_by_names),
url(r"^doc/submitted_to_rpc/$", views_rpc.submitted_to_rpc),
url(r"^doc/rfc/original_stream/$", views_rpc.rfc_original_stream),
url(r"^draft/by_names/", views_rpc.DraftsByNamesView.as_view()),
url(r"^doc/rfc/authors/$", views_rpc.rfc_authors),
url(r"^person/create_demo_person/$", views_rpc.create_demo_person),
url(r"^person/persons_by_email/$", views_rpc.persons_by_email),
url(r"^person/(?P<person_id>[0-9]+)$", views_rpc.rpc_person),
url(r"^persons/$", views_rpc.rpc_persons),
url(r"^subject/(?P<subject_id>[0-9]+)/person/$", views_rpc.rpc_subject_person),
path(r"subject/<str:subject_id>/person/", views_rpc.SubjectPersonView.as_view()),
path("", include(router.urls)), # todo get rid of drf prefix when done converting
]
Loading