So I have this code below for checking a AWS Cognito token. I obviously don't want to add these 6 lines of code to every endpoint. Also I don't know if this is the proper way of validating all I'm doing is expecting the token to be of format ' ', parsing it and just decoding the JWT token part. How can I authenticate the AWS amplify token that comes with every request to ensure the user is properly logged in. I'd like to add this authentication to APIView endpoints and DRF api_view decorated endpoints.
views.py
import django.db.utils
from rest_framework import authentication, permissions, status
from rest_framework.views import APIView
from .serializers import *
from .models import *
from rest_framework.response import Response
from django.http import JsonResponse
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from .core.api import jwt
from django.core.exceptions import ObjectDoesNotExist
class LoginView(APIView):
def post(self, request):
# 'Bearer z324weroko2iorjqoi=+3r3+3ij.2o2ij4='
token = request.META['HTTP_AUTHORIZATION'].split(' ')[1]
print(token)
# TODO this should be separated out to a login module
try:
res = jwt.decode_cognito_jwt(token)
return Response(status=status.Http_200_OK)
except:
return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED)
@api_view(['GET'])
@swagger_auto_schema(
operation_description="Get Goals joined by User"
)
def get_goals_by_user(request, user_id):
try:
# Get goal ids of user with id
goals_query = JoinGoal.objects.filter(
joiner_id=user_id).values_list('goal_id', flat=True)
goals_list = list(goals_query)
# Get Goals using list of goals PK with descriptions and uuid
data = list(Goal.objects.filter(
pk__in=goals_list).values('description', 'uuid'))
response_data = dict(goals=data)
return JsonResponse(response_data, status=status.HTTP_200_OK)
except JoinGoal.DoesNotExist:
return Response(dict(error=does_not_exist_msg(JoinGoal.__name__, 'joiner_id', user_id)), status=status.HTTP_400_BAD_REQUEST)