2020-10-03 21:37:58 +00:00
|
|
|
"""Tokens API Viewset"""
|
2020-10-18 12:34:22 +00:00
|
|
|
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)
|
2020-10-19 12:35:22 +00:00
|
|
|
def view_key(self, request: Request, identifier: str) -> Response:
|
2020-10-18 12:34:22 +00:00
|
|
|
"""Return token key and log access"""
|
2020-10-19 12:35:22 +00:00
|
|
|
tokens = Token.filter_not_expired(identifier=identifier)
|
2020-10-18 12:34:22 +00:00
|
|
|
if not tokens.exists():
|
|
|
|
raise Http404
|
|
|
|
token = tokens.first()
|
|
|
|
Event.new(EventAction.TOKEN_VIEW, token=token).from_http(request)
|
|
|
|
return Response({"key": token.key})
|