Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring #96

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ include =
**/serializers.py
**/views.py
**/models.py
api/utils.py
omit =
**/venv/**
**/virtualenv/**
2 changes: 1 addition & 1 deletion api/parties/comments/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Meta:
fields = ['text']

def validate(self, attrs):
slug = self.context['request'].path_info.split('/')[3]
slug = self.context['view'].kwargs['party_slug']
party = Party.objects.get(slug=slug)
author = self.context['request'].user.profile

Expand Down
2 changes: 1 addition & 1 deletion api/parties/comments/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
from api.parties.comments.views import CommentAPIViewSet

router = SimpleRouter()
router.register('', CommentAPIViewSet)
router.register('', CommentAPIViewSet, base_name='comment')

urlpatterns = router.urls
7 changes: 3 additions & 4 deletions api/parties/comments/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,21 @@


class CommentAPIViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.filter(is_active=True)
lookup_field = 'slug'
permission_classes = [CommentAPIPermission]
pagination_class = None

def get_queryset(self):
slug = self.kwargs['party_slug']
queryset = Comment.objects.filter(
party__slug=slug).order_by('created_at')
queryset = Comment.objects.filter(party__slug=slug)
for instance in queryset:
instance.party.update_party_info()
return queryset
return queryset.order_by('created_at')

def get_object(self):
instance = super(CommentAPIViewSet, self).get_object()
instance.party.update_party_info()
self.check_object_permissions(self.request, instance)
return instance

def get_serializer_class(self):
Expand Down
3 changes: 2 additions & 1 deletion api/parties/owner/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def get_object(self):
slug=self.kwargs['party_slug']
)
instance.update_party_info()
self.check_object_permissions(self.request, instance)
return instance

def get_serializer_class(self):
Expand Down Expand Up @@ -49,5 +50,5 @@ def update(self, request, *args, **kwargs):
)
)
return Response(PartyOwnerSerializer(instance).data)
except Exception as e:
except ValueError as e:
raise ValidationError(detail=str(e))
9 changes: 5 additions & 4 deletions api/parties/participants/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from rest_framework import serializers

from api.profiles.serializers import ProfileUsernamePictureSerializer
Expand All @@ -12,12 +12,13 @@ class Meta:
model = Party
fields = ['title', 'current_people', 'participants']

@staticmethod
def _set_profile_picture_url(data):
def _set_profile_picture_url(self, data):
domain = get_current_site(self.context['request'])
for datum in data:
if datum['profile_picture']:
pass
datum['profile_picture'] = \
'{}{}'.format(settings.HOST, datum['profile_picture'])
'http://{}{}'.format(domain, datum['profile_picture'])
return data

def get_participants(self, instance):
Expand Down
5 changes: 3 additions & 2 deletions api/parties/participants/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def get_object(self):
slug=self.kwargs['party_slug']
)
instance.update_party_info()
self.check_object_permissions(self.request, instance)
return instance

def _get_party_and_profile(self, request):
Expand All @@ -42,13 +43,13 @@ def create(self, request, *args, **kwargs):
)
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
except Exception as e:
except ValueError as e:
raise ValidationError(detail=str(e))

def destroy(self, request, *args, **kwargs):
instance, profile = self._get_party_and_profile(request)
try:
instance.remove_participants(participant=profile)
return Response(status=status.HTTP_204_NO_CONTENT)
except Exception as e:
except ValueError as e:
raise ValidationError(detail=str(e))
4 changes: 2 additions & 2 deletions api/parties/permissions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework import permissions
from rest_framework.permissions import IsAuthenticated


class PartyAPIPermission(permissions.IsAuthenticated):
class PartyAPIPermission(IsAuthenticated):
def has_object_permission(self, request, view, obj):
if request.method != 'GET':
has_permission = obj.party_owner == request.user.profile
Expand Down
35 changes: 35 additions & 0 deletions api/parties/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.utils import timezone
from rest_framework import serializers
from apps.parties.models import Party
from api.profiles.serializers import ProfileUsernamePictureSerializer
Expand Down Expand Up @@ -25,6 +26,22 @@ class Meta:
'max_people'
]

def validate(self, attrs):
max_people = attrs.get('max_people')
start_time = attrs.get('start_time')

today = timezone.localtime()
date_difference = (start_time - today).days

if date_difference < 0:
msg = '현재 시각 이전에 시작하는 파티를 주최할 수 없습니다'
raise serializers.ValidationError(msg)
if max_people < 2:
msg = '참여 가능 인원은 2명 이상이어야 합니다'
raise serializers.ValidationError(msg)

return attrs

def create(self, validated_data):
model_class = self.Meta.model
user = self.context['request'].user
Expand All @@ -47,6 +64,24 @@ class Meta:
'max_people'
]

def validate(self, attrs):
start_time = attrs.get('start_time')
max_people = attrs.get('max_people')

if start_time:
today = timezone.localtime()
date_difference = (start_time - today).days
if date_difference < 0:
msg = '파티의 시작 시간을 현재 시각보다 빠르게 설정할 수 없습니다.'
raise serializers.ValidationError(msg)

if max_people:
if max_people < self.instance.current_people:
msg = '파티의 최대 인원을 현재 인원보다 작게 설정할 수 없습니다.'
raise serializers.ValidationError(msg)

return attrs

def update(self, instance, validated_data):
return Party.objects.update_party(
instance,
Expand Down
2 changes: 1 addition & 1 deletion api/parties/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
]

router = routers.SimpleRouter()
router.register('', PartyAPIViewSet)
router.register('', PartyAPIViewSet, base_name='party')

urlpatterns += router.urls
43 changes: 12 additions & 31 deletions api/parties/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from rest_framework import status, viewsets
from rest_framework.exceptions import ValidationError, APIException
from rest_framework import viewsets
from rest_framework.generics import ListAPIView, get_object_or_404
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.response import Response
Expand All @@ -14,7 +13,6 @@


class PartyAPIViewSet(viewsets.ModelViewSet):
queryset = Party.objects.all()
lookup_field = 'party_slug'
pagination_class = PartyAPIPagination
permission_classes = [PartyAPIPermission]
Expand All @@ -31,7 +29,7 @@ class PartyAPIViewSet(viewsets.ModelViewSet):
}

def get_queryset(self):
queryset = super(PartyAPIViewSet, self).get_queryset()
queryset = Party.objects.all()
for instance in queryset:
instance.update_party_info()
return queryset
Expand All @@ -41,22 +39,12 @@ def get_object(self):
self.get_queryset(),
slug=self.kwargs['party_slug']
)
self.check_object_permissions(self.request, instance)
return instance

def get_serializer_class(self):
return self.SERIALIZERS[self.request.method]

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
except ValueError as e:
raise ValidationError(detail=str(e))
except Exception as e:
raise APIException(detail=str(e))

def update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(
Expand All @@ -65,23 +53,16 @@ def update(self, request, *args, **kwargs):
partial=True
)
serializer.is_valid(raise_exception=True)
try:
self.perform_update(serializer)

send_push_to_multiple_user(
[participant for participant in instance.participants.all()],
instance,
'[파티 정보 수정됨]',
'[{}] 의 정보가 수정되었습니다.'.format(
instance.title
)
self.perform_update(serializer)
send_push_to_multiple_user(
[participant for participant in instance.participants.all()],
instance,
'[파티 정보 수정됨]',
'[{}] 의 정보가 수정되었습니다.'.format(
instance.title
)

return Response(serializer.data)
except ValueError as e:
raise ValidationError(detail=str(e))
except Exception as e:
raise APIException(detail=str(e))
)
return Response(serializer.data)


class JoinedPartyAPIView(ListAPIView):
Expand Down
2 changes: 0 additions & 2 deletions api/users/forgot/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from api.users.forgot.views import ForgotPasswordAPIView

app_name = 'forgot'

urlpatterns = [
path('', ForgotPasswordAPIView.as_view())
]
Empty file added api/users/login/__init__.py
Empty file.
34 changes: 34 additions & 0 deletions api/users/login/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from rest_framework import serializers
from rest_framework.compat import authenticate


class LoginSerializer(serializers.Serializer):
fcm_token = serializers.CharField(max_length=300)
email = serializers.EmailField(label='이메일')
password = serializers.CharField(
label='비밀번호',
style={
'input_type': 'password'
},
trim_whitespace=False
)

def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')

if email and password:
user = authenticate(
request=self.context.get('request'),
email=email,
password=password
)
if not user:
msg = '이메일 혹은 비밀번호가 잘못되었습니다'
raise serializers.ValidationError(msg, code='authorization')
else:
msg = '이메일과 비밀번호는 필수 항목입니다'
raise serializers.ValidationError(msg, code='authorization')

attrs['user'] = user
return attrs
34 changes: 34 additions & 0 deletions api/users/login/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from rest_framework import generics
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from api.users.serializers import UserSerializer
from api.users.login.serializers import LoginSerializer
from apps.users.models import User


class LoginAPIView(generics.GenericAPIView):
permission_classes = [AllowAny]
serializer_class = LoginSerializer

def post(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
user.update_fcm_token(serializer.validated_data['fcm_token'])
User.objects.reactivate_user(user)
token, created = Token.objects.get_or_create(user=user)

data = UserSerializer(user).data
data['token'] = token.key
data['profile_picture'] = \
'http://{}{}{}'.format(
get_current_site(self.request),
settings.MEDIA_URL,
user.profile.profile_picture
)

return Response(data)
4 changes: 2 additions & 2 deletions api/users/permissions.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from rest_framework import permissions
from rest_framework.permissions import BasePermission


class UserAPIPermission(permissions.BasePermission):
class UserAPIPermission(BasePermission):
def has_permission(self, request, view):
if request.method == 'POST':
return True
Expand Down
33 changes: 0 additions & 33 deletions api/users/serializers.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,8 @@
from rest_framework import serializers
from rest_framework.compat import authenticate

from apps.users.models import User


class LoginSerializer(serializers.Serializer):
fcm_token = serializers.CharField(max_length=300)
email = serializers.EmailField(label='이메일')
password = serializers.CharField(
label='비밀번호',
style={
'input_type': 'password'
},
trim_whitespace=False
)

def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')

if email and password:
user = authenticate(
request=self.context.get('request'),
email=email,
password=password
)
if not user:
msg = '이메일 혹은 비밀번호가 잘못되었습니다.'
raise serializers.ValidationError(msg, code='authorization')
else:
msg = '이메일과 비밀번호는 필수 항목입니다'
raise serializers.ValidationError(msg, code='authorization')

attrs['user'] = user
return attrs


class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
Expand Down
Loading