added user-specific endpoints

This commit is contained in:
Sam
2021-02-04 10:14:28 +00:00
parent ea8cd97baf
commit 77acc668b8
7 changed files with 145 additions and 9 deletions

View File

@@ -239,3 +239,38 @@ class CompanyViewSetTest(APITestCase):
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
# Assert instance doesn't exists anymore on db
self.assertFalse(self.model.objects.filter(id=instance.pk).exists())
class MyCompanyViewTest(APITestCase):
"""CompanyViewset tests
"""
def setUp(self):
"""Tests setup
"""
self.endpoint = '/api/v1/my_company/'
self.factory = CompanyFactory
self.model = Company
# create user
self.email = f"user@mail.com"
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
self.user = CustomUserFactory(email=self.email, is_active=True)
self.user.set_password(self.password)
self.user.save()
def test_auth_user_gets_data(self):
# Authenticate
token = get_tokens_for_user(self.user)
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}")
# Query endpoint
response = self.client.get(self.endpoint)
# Assert forbidden code
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_anon_user_cannot_access(self):
# send in request
response = self.client.get(self.endpoint)
# check response
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

View File

@@ -1,8 +1,11 @@
from django.shortcuts import render
from django.core import serializers
from rest_framework.decorators import api_view, permission_classes
# Create your views here.
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from companies.models import Company
from companies.serializers import CompanySerializer
@@ -14,3 +17,11 @@ class CompanyViewSet(viewsets.ModelViewSet):
queryset = Company.objects.all()
serializer_class = CompanySerializer
permission_classes = [IsAuthenticatedOrReadOnly, IsCreator]
@api_view(['GET',])
@permission_classes([IsAuthenticated,])
def my_company(request):
qs = Company.objects.filter(creator=request.user)
data = serializers.serialize('json', qs)
return Response(data=data)