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

All Tasks Done #13

Open
wants to merge 10 commits into
base: master
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
26 changes: 26 additions & 0 deletions api/migrations/0003_auto_20210807_1729.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 3.0.7 on 2021-08-07 11:59

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0002_todo_creator'),
]

operations = [
migrations.AddField(
model_name='todo',
name='contributors',
field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name='Contributors'),
),
migrations.AlterField(
model_name='todo',
name='creator',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='todo_requests_created', to=settings.AUTH_USER_MODEL),
),
]
7 changes: 5 additions & 2 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@


class Todo(models.Model):
creator = models.ForeignKey(User, on_delete=models.CASCADE)
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='%(class)s_requests_created')
contributors = models.ManyToManyField(
"auth.User", verbose_name=("Contributors"))
title = models.CharField(max_length=255)

def __str__(self):
return self.title
return self.title
14 changes: 14 additions & 0 deletions api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.contrib.auth.models import User
from django.db.models import fields
from rest_framework import serializers
from .models import Todo

Expand All @@ -23,7 +25,19 @@ def save(self, **kwargs):
user = self.context['request'].user
title = data['title']
todo = Todo.objects.create(creator=user, title=title)
return todo.id

class Meta:
model = Todo
fields = ('id', 'title',)


class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title',)

class CollaboratorSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
9 changes: 7 additions & 2 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.urls import path
from .views import TodoCreateView
from .views import *

"""
TODO:
Expand All @@ -9,4 +9,9 @@

urlpatterns = [
path('todo/create/', TodoCreateView.as_view()),
]
path('todo/', TodoGetView.as_view()),
path('todo/<int:id>', TodoGetSpecificView.as_view()),
path('todo/<int:id>/add-collaborators/', TodoAddColaboratorsView.as_view()),
path('todo/<int:id>/remove-collaborators/', TodoRemoveColaboratorsView.as_view()),

]
206 changes: 203 additions & 3 deletions api/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from django.db.models.fields import mixins
from rest_framework import generics
from rest_framework import permissions
from rest_framework import status
from rest_framework import mixins
from rest_framework import response
from rest_framework.response import Response
from .serializers import TodoCreateSerializer
from .serializers import *
from .models import Todo
from django.db.models import Q
from django.contrib.auth.models import User
from rest_framework.authentication import SessionAuthentication, BasicAuthentication


"""
Expand All @@ -13,6 +19,115 @@
"""


class TodoGetView(generics.GenericAPIView):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# uncomment the above line to check in postman
permission_classes = (permissions.IsAuthenticated, )
def get(self, request):
taskSelf=Todo.objects.filter(creator=request.user)
taskOther = Todo.objects.filter(contributors=request.user)
serializer1= TodoSerializer(taskSelf, many = True)
serializer2 = TodoSerializer(taskOther, many=True)
response=[]
for x in serializer1.data:
todo = Todo.objects.get(id=x['id'])
response.append({
'id': todo.id,
'title': todo.title,
'creator': todo.creator.username
})
for t in serializer2.data:
todo = Todo.objects.get(id=t['id'])
response.append({
'id': todo.id,
'title': todo.title,
'creator': todo.creator.username
})
return Response(response,status=status.HTTP_200_OK)



class TodoGetSpecificView(generics.GenericAPIView, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# uncomment the above line to check in postman
permission_classes = (permissions.IsAuthenticated, )
serializer_class = TodoSerializer
queryset = Todo.objects.all()
lookup_field = 'id'

def put(self, request, id=None):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({"Todo with the following id does not exist"}, status=status.HTTP_404_NOT_FOUND)
queryset = Todo.objects.filter(Q(creator=request.user) | Q(
contributors=request.user))
x = False
for todos in queryset:
if todos == todo:
x = True
if x:
return self.update(request, id)
else:
return Response({"You dont have permission to edit this todo"}, status=status.HTTP_403_FORBIDDEN)

def patch(self, request, id=None):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({"Todo with the following id does not exist"}, status=status.HTTP_404_NOT_FOUND)
queryset = Todo.objects.filter(Q(creator=request.user) | Q(
contributors=request.user))
x = False
for todos in queryset:
if todos == todo:
x = True
if x:
return self.update(request, id)
else:
return Response({"You dont have permission to edit this todo"}, status=status.HTTP_403_FORBIDDEN)

def get(self, request, id=None):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({"Todo with the following id does not exist"} , status=status.HTTP_404_NOT_FOUND)

response=[]
if todo.creator==request.user:
response.append({
'id': todo.id,
'title': todo.title,
'role': 'creator'
})
return Response(response, status=status.HTTP_200_OK)
elif request.user in todo.contributors.all():
response.append({
'id': todo.id,
'title': todo.title,
'role': 'collaborator'
})
return Response(response, status=status.HTTP_200_OK)
else:
return Response({"You dont have permission to view this todo"}, status=status.HTTP_403_FORBIDDEN)

def delete(self, request, id):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({"Todo with the following id does not exist"}, status=status.HTTP_404_NOT_FOUND)
queryset = Todo.objects.filter(Q(creator=request.user) | Q(
contributors=request.user))
x = False
for todos in queryset:
if todos == todo:
x = True
if x:
return self.destroy(request, id)
else:
return Response({"You dont have permission to delete this todo"}, status=status.HTTP_403_FORBIDDEN)


class TodoCreateView(generics.GenericAPIView):
"""
TODO:
Expand All @@ -22,14 +137,99 @@ class TodoCreateView(generics.GenericAPIView):
Modify the below code (if required), so that this endpoint would
also return the serialized Todo data (id etc.), alongwith 200 status code.
"""
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# uncomment the above line to check in postman
permission_classes = (permissions.IsAuthenticated, )
serializer_class = TodoCreateSerializer

def post(self, request):

"""
Creates a Todo entry for the logged in user.
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_200_OK)
id = serializer.save()
return Response({
"id": id,
"title": request.data.get('title')
}, status=status.HTTP_201_CREATED)


class TodoAddColaboratorsView(generics.GenericAPIView):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# uncomment the above line to check in postman
permission_classes = (permissions.IsAuthenticated, )
serializer_class = CollaboratorSerializer
lookup_field = 'id'

def post(self, request, id=None):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({
"Todo with the following id does not exists"
}, status=status.HTTP_404_NOT_FOUND)
if todo.creator == request.user:
try:
collaborator = User.objects.get(
username__exact=request.data.get('username'))
if collaborator == request.user:
return Response({
"You cannot add yourself as a collaborator since you are the creator of this todo"
}, status=status.HTTP_403_FORBIDDEN)
else:
todo.contributors.add(collaborator)
todo.save()
except:
return Response({
"User with this username does not exists"
}, status=status.HTTP_404_NOT_FOUND)
else:
return Response({
"You dont have permissions to add collaborators to this todo"
}, status=status.HTTP_403_FORBIDDEN)

return Response({
"Collaborator added succesfully"
}, status=status.HTTP_200_OK)


class TodoRemoveColaboratorsView(generics.GenericAPIView):
# authentication_classes = [SessionAuthentication, BasicAuthentication]
# uncomment the above line to check in postman
permission_classes = (permissions.IsAuthenticated, )
serializer_class = CollaboratorSerializer
lookup_field = 'id'

def put(self, request, id=None):
try:
todo = Todo.objects.get(id__exact=id)
except:
return Response({
"Todo with the following id does not exists"
}, status=status.HTTP_404_NOT_FOUND)
if todo.creator == request.user:
try:
collaborator = User.objects.get(
username__exact=request.data.get('username'))
if collaborator == request.user:
return Response({
"You cannot remove yourself from collaborators since you are the creator of this todo"
}, status=status.HTTP_403_FORBIDDEN)
else:
todo.contributors.remove(collaborator)
todo.save()

except:
return Response({
"User with this username does not exists"
}, status=status.HTTP_404_NOT_FOUND)
else:
return Response({
"You dont have permissions to remove collaborators from this todo"
}, status=status.HTTP_403_FORBIDDEN)

return Response({
"Collaborator removed succesfully"
},status=status.HTTP_200_OK)
31 changes: 24 additions & 7 deletions authentication/serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.core.validators import MaxLengthValidator
from rest_framework import serializers
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
Expand All @@ -7,17 +8,33 @@ class TokenSerializer(serializers.Serializer):
token = serializers.CharField(max_length=500)


class LoginSerializer(serializers.Serializer):
class LoginSerializer(serializers.ModelSerializer):
# TODO: Implement login functionality
pass
class Meta:
model = User
fields = ('username', 'password')


class RegisterSerializer(serializers.Serializer):
class RegisterSerializer(serializers.ModelSerializer):
# TODO: Implement register functionality
pass

class Meta:
model = User
fields = ('first_name', 'email', 'username', 'password')

def create(self, validated_data):
user = User(
first_name=validated_data['first_name'],
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user

class UserSerializer(serializers.ModelSerializer):
# TODO: Implement the functionality to display user details
pass

class Meta:
model = User
fields = ('id', 'first_name', 'email', 'username')


Loading