2020-10-03 21:37:58 +00:00
|
|
|
"""Tokens API Viewset"""
|
2020-10-18 12:34:22 +00:00
|
|
|
from uuid import UUID
|
|
|
|
|
|
|
|
from django.http.response import Http404
|
|
|
|
from rest_framework.decorators import action
|
|
|
|
from rest_framework.request import Request
|
|
|
|
from rest_framework.response import Response
|
2020-10-03 21:37:58 +00:00
|
|
|
from rest_framework.serializers import ModelSerializer
|
|
|
|
from rest_framework.viewsets import ModelViewSet
|
|
|
|
|
2020-10-18 12:34:22 +00:00
|
|
|
from passbook.audit.models import Event, EventAction
|
2020-10-03 21:37:58 +00:00
|
|
|
from passbook.core.models import Token
|
|
|
|
|
|
|
|
|
|
|
|
class TokenSerializer(ModelSerializer):
|
|
|
|
"""Token Serializer"""
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
|
|
|
model = Token
|
|
|
|
fields = ["pk", "identifier", "intent", "user", "description"]
|
|
|
|
|
|
|
|
|
|
|
|
class TokenViewSet(ModelViewSet):
|
|
|
|
"""Token Viewset"""
|
|
|
|
|
|
|
|
lookup_field = "identifier"
|
2020-10-18 12:34:22 +00:00
|
|
|
queryset = Token.filter_not_expired()
|
2020-10-03 21:37:58 +00:00
|
|
|
serializer_class = TokenSerializer
|
2020-10-18 12:34:22 +00:00
|
|
|
|
|
|
|
@action(detail=True)
|
|
|
|
# pylint: disable=invalid-name
|
|
|
|
def view_key(self, request: Request, pk: UUID) -> Response:
|
|
|
|
"""Return token key and log access"""
|
|
|
|
tokens = Token.filter_not_expired(pk=pk)
|
|
|
|
if not tokens.exists():
|
|
|
|
raise Http404
|
|
|
|
token = tokens.first()
|
|
|
|
Event.new(EventAction.TOKEN_VIEW, token=token).from_http(request)
|
|
|
|
return Response({"key": token.key})
|