Skip to content

Commit

Permalink
Merge 1953b5c into c20694e
Browse files Browse the repository at this point in the history
  • Loading branch information
mulondo committed Jan 15, 2019
2 parents c20694e + 1953b5c commit 7b80f38
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 39 deletions.
9 changes: 7 additions & 2 deletions authors/apps/authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from rest_framework import status
from rest_framework.generics import RetrieveUpdateAPIView
from rest_framework.permissions import (AllowAny,IsAuthenticated,IsAuthenticatedOrReadOnly)
from rest_framework.permissions import (
AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly)
from rest_framework.response import Response
from rest_framework.views import APIView
from .validations import validate_registration
Expand All @@ -21,6 +22,8 @@
LoginSerializer, RegistrationSerializer, UserSerializer, PasswordSerializer
)
from .models import User
from ..profiles.serializers import GetUserProfileSerializer
from ..profiles.models import UserProfile
from authors.apps.articles.models import Article
from django.http import JsonResponse

Expand Down Expand Up @@ -202,6 +205,8 @@ def get(self, request):
serializer = self.serializer_class(users, many=True)
response = {'authors': serializer.data}
for author, obj in zip(response['authors'], User.objects.all()):
author['profile'] = reverse('profile', request=request)
userprofile = UserProfile.objects.get(user=obj.id)
userprofile_serializer = GetUserProfileSerializer(userprofile)
author['profile'] = userprofile_serializer.data
del author['token']
return JsonResponse(response, status=200, safe=False)
38 changes: 21 additions & 17 deletions authors/apps/profiles/tests/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@


class TestUserProfile(APITestCase):

def setUp(self):
self.user_data = {"user": { "username":"minime", "email": "alexkayabula@gmail.com", "password":"W123456/78"}}
self.user_data = {"user": {"username": "minime",
"email": "alexkayabula@gmail.com", "password": "W123456/78"}}
self.url = reverse("registration")
self.client = APIClient()
self.client.post(self.url, self.user_data, format='json')
Expand All @@ -23,36 +24,39 @@ def setUp(self):
response = self.account_verification(token, uid)
self.assertEqual(response.status_code, status.HTTP_200_OK)
user = User.objects.get()
self.assertTrue(user.is_verified)
self.assertTrue(user.is_verified)

response = self.client.post('/api/users/login/',self.user_data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.post(
'/api/users/login/', self.user_data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.login_token = response.data['token']
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.login_token)


self.client.credentials(
HTTP_AUTHORIZATION='Bearer ' + self.login_token)

def account_verification(self, token, uid):
request = APIRequestFactory().get(
reverse("verify_account", kwargs={"token": token, "uid":uid})
reverse("verify_account", kwargs={"token": token, "uid": uid})
)
verify = AccountVerified.as_view()
response = verify(request, token=token, uid=uid)
return response

def test_get_a_list_of_userprofiles(self):

def test_get_a_list_of_userprofiles(self):

response = self.client.get('/api/users/profiles', format='json')

self.assertEqual(response.status_code, status.HTTP_200_OK)



def test_update_profile(self):
update_data = {"bio":"I have been doing programming since 1995",
"fun_fact":"I love dancing"
}
update_data = {"bio": "I have been doing programming since 1995",
"fun_fact": "I love dancing"
}

response = self.client.put(
'/api/users/profiles/', update_data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)

response = self.client.put('/api/users/profiles/', update_data, format ='json')
def test_logged_in_userprofile(self):
response = self.client.get(
'/api/users/profiles/',format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
48 changes: 28 additions & 20 deletions authors/apps/profiles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
)
from rest_framework import generics, viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated,IsAuthenticatedOrReadOnly
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.views import APIView
from rest_framework import status
from .models import UserProfile, Follow
Expand All @@ -25,35 +25,40 @@ class Updateprofile(RetrieveUpdateAPIView):
queryset = UserProfile.objects.all()
serializer_class = UpdateProfileSerializer

def update(self,request):
serializer =self.serializer_class(request.user.userprofile, data=request.data)
def update(self, request):
serializer = self.serializer_class(
request.user.userprofile, data=request.data)
serializer.is_valid(raise_exception=True)
serializer.update(request.user.userprofile, request.data)
return Response(serializer.data)

def get(self, request):
serializer = self.serializer_class(request.user.userprofile)
return Response(serializer.data)


class FavoriteArticle(RetrieveUpdateAPIView):
permission_classes = (IsAuthenticatedOrReadOnly,)
serializer_class = FavoriteArticleSerializer
queryset = Article.objects.all()

def update(self,request,slug):
def update(self, request, slug):
try:
serializer_instance = self.queryset.get(slug=slug)
except Article.DoesNotExist:
return Response('An article with this slug does not exist.',status.HTTP_404_NOT_FOUND)
return Response('An article with this slug does not exist.', status.HTTP_404_NOT_FOUND)

userprofile_obj = request.user.userprofile

if slug in userprofile_obj.favorite_article:
userprofile_obj.favorite_article.remove(slug)
userprofile_obj.save()
userprofile_obj.save()
return Response("unfavorited!")

userprofile_obj.favorite_article.append(slug)
userprofile_obj.save(update_fields = ['favorite_article'])
userprofile_obj.save(update_fields=['favorite_article'])
return Response("favorited!")


class FollowsView(APIView):
permission_classes = (IsAuthenticated,)
Expand All @@ -63,7 +68,8 @@ def post(self, request, username):
try:
followed_id = User.objects.get(username=username).id
self.profile_id = UserProfile.objects.get(user_id=followed_id).id
self.verify_following_criteria_met(follower_id, followed_id, username)
self.verify_following_criteria_met(
follower_id, followed_id, username)
except Exception as e:
if isinstance(e, User.DoesNotExist):
raise NotFound('No user with name {} exists.'.format(username))
Expand All @@ -74,29 +80,32 @@ def post(self, request, username):
serializer.save()
profile = self.get_followed_profile(self.profile_id)
return Response(profile, status=status.HTTP_201_CREATED)

def verify_following_criteria_met(self, follower_id, followed_id, name):
if follower_id == followed_id:
raise Exception('You cannot follow your own profile.')
query_result = Follow.objects.filter(follower_id=follower_id, followed_id=self.profile_id)
query_result = Follow.objects.filter(
follower_id=follower_id, followed_id=self.profile_id)
if len(query_result) != 0:
raise Exception('Already following {}.'.format(name))

def get_followed_profile(self, followed):
profile = UserProfile.objects.get(id=followed)
serializer = GetUserProfileSerializer(profile)
profile = serializer.data
profile['following'] = True
return profile

def delete(self, request, username):
user_id = User.objects.get(username=request.user.username).id
try:
followed_id = User.objects.get(username=username).id
profile_id = UserProfile.objects.get(user_id=followed_id).id
follow = Follow.objects.filter(follower_id=user_id, followed_id=profile_id)
follow = Follow.objects.filter(
follower_id=user_id, followed_id=profile_id)
if len(follow) == 0:
raise Exception('Cannot unfollow a user you are not following.')
raise Exception(
'Cannot unfollow a user you are not following.')
follow.delete()
return Response(
{'message': 'Successfully unfollowed {}.'.format(username)},
Expand All @@ -111,7 +120,7 @@ def delete(self, request, username):
return Response(
{'error': str(e)}, status=status.HTTP_400_BAD_REQUEST
)

def get(self, request, username):
try:
user_id = User.objects.get(username=username).id
Expand Down Expand Up @@ -143,4 +152,3 @@ def get(self, request, username):
username = User.objects.get(id=follow['follower']).username
followers.append(username)
return Response({'followers': followers}, status=status.HTTP_200_OK)

0 comments on commit 7b80f38

Please sign in to comment.