def get(self, _request): user = JWTAuthentication.get_user(self, _request) # only get the plants that belong to the user who is signed in plants = Plant.objects.all().filter(user=user) serializer = SimplifiedPlantsSerializer(plants, many=True) return Response(serializer.data, status=HTTP_200_OK) # send the JSON to the client
def delete(self, request, pk): user = JWTAuthentication.get_user(self, request) plant = Plant.objects.get(pk=pk) if plant.user.id != user: return Response(status=HTTP_401_UNAUTHORIZED) plant.delete() return Response(status=HTTP_204_NO_CONTENT)
def test_not_jwt(): """Test when the token is not a JWT """ header_string = 'some random string' request = HttpRequest() request.META['HTTP_AUTHORIZATION'] = header_string assert JWTAuthentication().authenticate(request) is None
def test_with_www(): """Test authenticate_header function when host www prefix """ request = HttpRequest() request.META['HTTP_HOST'] = 'www.example.com' expected = 'aps.example.com/user/accounts/login/' actual = JWTAuthentication().authenticate_header(request) assert actual == expected
def test_bad_jwt(): """Test when we have a bad JWT """ header_string = 'JWT some random string' request = HttpRequest() request.META['HTTP_AUTHORIZATION'] = header_string with pytest.raises(AuthenticationFailed): print(JWTAuthentication().authenticate(request))
def get(self, _request, pk): user = JWTAuthentication.get_user(self, _request) plant = Plant.objects.get(pk=pk) if plant.user.id != user: return Response(status=HTTP_401_UNAUTHORIZED) serializer = PopulatedPlantSerializer(plant) return Response(serializer.data, status=HTTP_200_OK) # send the JSON to the client
def put(self, request, pk): user = JWTAuthentication.get_user(self, request) plant = Plant.objects.get(pk=pk) if plant.user.id != user: return Response(status=HTTP_401_UNAUTHORIZED) updated_plant = PlantsSerializer(plant, data=request.data) if updated_plant.is_valid(): updated_plant.save() return Response(updated_plant.data) return Response(updated_plant.errors, status=HTTP_422_UNPROCESSABLE_ENTITY)
def patch(self, request, pk): try: userAuth = JWTAuthentication.authenticate(self, request) user = request.user updated_user = UserSerializer(user, data=request.data, context={'is_create': False}, partial=True) if updated_user.is_valid(): updated_user.save() return Response(updated_user.data, status=HTTP_202_ACCEPTED) return Response(updated_user.errors, status=HTTP_422_UNPROCESSABLE_ENTITY) except User.DoesNotExist: return Response({'message': 'Not Found'}, status=HTTP_404_NOT_FOUND)
def test_no_token(): """Test when there is no Authorization header """ request = HttpRequest() assert JWTAuthentication().authenticate(request) is None