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 Completed #15

Open
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion api/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.contrib import admin
from .models import Todo
from .models import *

admin.site.register(Todo)
20 changes: 20 additions & 0 deletions api/migrations/0003_todo_collaborator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.0.7 on 2021-08-07 14:32

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


class Migration(migrations.Migration):

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

operations = [
migrations.AddField(
model_name='todo',
name='collaborator',
field=models.ManyToManyField(related_name='task_collaborator', to=settings.AUTH_USER_MODEL),
),
]
20 changes: 20 additions & 0 deletions api/migrations/0004_auto_20210807_2213.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 3.0.7 on 2021-08-07 16:43

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


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0003_todo_collaborator'),
]

operations = [
migrations.AlterField(
model_name='todo',
name='collaborator',
field=models.ManyToManyField(related_name='collaborator', to=settings.AUTH_USER_MODEL),
),
]
3 changes: 3 additions & 0 deletions api/models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.db.models.deletion import CASCADE


class Todo(models.Model):
creator = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
collaborator = models.ManyToManyField(User,related_name='collaborator')

def __str__(self):
return self.title
23 changes: 22 additions & 1 deletion api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import serializers
from .models import Todo
from .models import *


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

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

class TodoSerializer(serializers.ModelSerializer):

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

class CollaboratorSerializer(serializers.ModelSerializer):

collaborator_username = serializers.CharField(required=True, max_length=255)

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


6 changes: 5 additions & 1 deletion 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,8 @@

urlpatterns = [
path('todo/create/', TodoCreateView.as_view()),
path('todo/<int:id>/', TodoCrudView.as_view()),
path('todo/', TodoListView.as_view()),
path('todo/<int:id>/add-collaborators/', AddCollaboratorView.as_view()),
path('todo/<int:id>/remove-collaborators/', RemoveCollaboratorView.as_view()),
]
153 changes: 150 additions & 3 deletions api/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from django.http.response import Http404, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework import generics
from rest_framework import permissions
from rest_framework import status
from rest_framework.response import Response
from .serializers import TodoCreateSerializer
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from .serializers import *
from .models import Todo
from django.contrib.auth.models import User


"""
Expand Down Expand Up @@ -31,5 +37,146 @@ def post(self, request):
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_200_OK)
response = serializer.save()
return Response(response,status=status.HTTP_200_OK)

class TodoListView(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated, )
serializer_class = TodoSerializer

def get(self, request):
task1 = Todo.objects.filter(creator=request.user)
task2 = Todo.objects.filter(collaborator=request.user)
serializer1 = self.get_serializer(task1, many = True)
serializer2 = self.get_serializer(task2, many = True)
response = []
for t in serializer1.data:
response.append(t)
for x in serializer2.data:
task = Todo.objects.get(id = x['id'])
response.append({'id' : task.id , 'title' : task.title , 'Todo_creator' : task.creator.username})

return Response(response, status = status.HTTP_200_OK)

class TodoCrudView(generics.GenericAPIView):

permission_classes = (permissions.IsAuthenticated, )
serializer_class = TodoSerializer

def get(self,request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')
if request.user == task.creator:
serializer = self.get_serializer(task,many = False)
return Response(serializer.data,status=status.HTTP_200_OK)
elif request.user in task.collaborator.all():
serializer = self.get_serializer(task,many = False)
response = []
response.append({'id' : task.id , 'title' : task.title , 'Todo_creator' : task.creator.username})
return Response(response, status = status.HTTP_200_OK)
else:
return Response("You are not allowed to get this task",status=status.HTTP_404_NOT_FOUND)

def put(self, request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')
if request.user==task.creator or request.user in task.collaborator.all():
serializer = self.get_serializer(task,many=False, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
else:
return Response("You cannot edit this task",status=status.HTTP_404_NOT_FOUND)

def patch(self, request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')
if request.user==task.creator or request.user in task.collaborator.all():
serializer = self.get_serializer(task,many=False, data=request.data, partial = True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
else:
return Response("You cannot edit this task",status=status.HTTP_404_NOT_FOUND)

def delete(self,request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')
if request.user==task.creator or request.user in task.collaborator.all():
task.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
else:
return Response("You cannot delete this task",status=status.HTTP_404_NOT_FOUND)

class AddCollaboratorView(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated, )
serializer_class = CollaboratorSerializer

def post(self,request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')

if task.creator == request.user:
try:
user = User.objects.get(username=request.data.get('collaborator_username'))
if user in task.collaborator.all():
return Response("This user is already a Collaborator in this task",status=status.HTTP_404_NOT_FOUND)
elif user==task.creator:
return Response("You are already creator of this Task",status=status.HTTP_404_NOT_FOUND)
else:
task.collaborator.add(user)
task.save()
return Response("Collaborator Added Successfully",status=status.HTTP_200_OK)
except User.DoesNotExist:
msg = ('User with this username does not exist')
raise serializers.ValidationError(msg, code='todo')
else:
msg = ('You are not the creator of this task')
raise serializers.ValidationError(msg, code='todo')

class RemoveCollaboratorView(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated, )
serializer_class = CollaboratorSerializer

def put(self,request,id):
try:
task = Todo.objects.get(id = id)
except Todo.DoesNotExist:
msg = ('Task with this Id does not exist')
raise serializers.ValidationError(msg, code='todo')

if task.creator == request.user:
try:
user = User.objects.get(username=request.data.get('collaborator_username'))
if user in task.collaborator.all():
task.collaborator.remove(user)
task.save()
return Response("Collaborator Removed Successfully",status=status.HTTP_200_OK)
elif user==task.creator:
return Response("You are already creator of this Task",status=status.HTTP_404_NOT_FOUND)
else:
return Response("This user is not a Collaborator of this task",status=status.HTTP_404_NOT_FOUND)

except User.DoesNotExist:
msg = ('User with this username does not exist')
raise serializers.ValidationError(msg, code='todo')
else:
msg = ('You are not the creator of this task')
raise serializers.ValidationError(msg, code='todo')


31 changes: 26 additions & 5 deletions authentication/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,38 @@ 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):
if User.objects.filter(email=validated_data['email']).exists():
msg = ('Email Id already exists')
raise serializers.ValidationError(msg, code='authentication')
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
)
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')

39 changes: 35 additions & 4 deletions authentication/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from rest_framework import permissions
from rest_framework import permissions, serializers
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from rest_framework.authtoken.views import ObtainAuthToken
from django.contrib.auth import authenticate
from .serializers import (
LoginSerializer, RegisterSerializer, UserSerializer, TokenSerializer)

Expand All @@ -21,16 +24,38 @@ class LoginView(generics.GenericAPIView):
Implement login functionality, taking username and password
as input, and returning the Token.
"""
pass
serializer_class = LoginSerializer

def post(self,request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'},
status=400)

user = authenticate(username=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},
status=404)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key})

class RegisterView(generics.GenericAPIView):
"""
TODO:
Implement register functionality, registering the user by
taking his details, and returning the Token.
"""
pass
serializer_class = RegisterSerializer

def post(self, request):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
token, created = Token.objects.get_or_create(user=serializer.instance)
return Response({
"token" : token.key
})


class UserProfileView(generics.RetrieveAPIView):
Expand All @@ -39,4 +64,10 @@ class UserProfileView(generics.RetrieveAPIView):
Implement the functionality to retrieve the details
of the logged in user.
"""
pass
permission_classes = (permissions.IsAuthenticated, )
serializer_class = UserSerializer

def get(self, request):
user = User.objects.get(username=self.request.user.username)
serializer = self.get_serializer(user)
return Response(serializer.data)