Skip to content

Commit

Permalink
Added user information to Tasks and added filtering for List view
Browse files Browse the repository at this point in the history
  • Loading branch information
dnstanciu committed Dec 22, 2018
1 parent 4d149cf commit c0d46c1
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 0 deletions.
19 changes: 19 additions & 0 deletions django/todoapi/migrations/0004_task_created_by.py
@@ -0,0 +1,19 @@
# Generated by Django 2.1.4 on 2018-12-21 14:08

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('todoapi', '0003_auth0user'),
]

operations = [
migrations.AddField(
model_name='task',
name='created_by',
field=models.CharField(default='dummy', max_length=200),
preserve_default=False,
),
]
2 changes: 2 additions & 0 deletions django/todoapi/models.py
Expand Up @@ -5,6 +5,8 @@
# Create the Task class to describe the model.
class Task(models.Model):
"""Stores a task."""
created_by = models.CharField(max_length=200)

title = models.CharField(max_length=50)
content = models.CharField(max_length=50)

Expand Down
4 changes: 4 additions & 0 deletions django/todoapi/serializers.py
Expand Up @@ -5,3 +5,7 @@ class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'content', 'created_on', 'due_date')

extra_kwargs = {
'created_by': { 'read_only': True }
}
7 changes: 7 additions & 0 deletions django/todoapi/utils.py
@@ -0,0 +1,7 @@
# For getting the username from the JWT token.
from rest_framework_jwt.utils import jwt_decode_handler

def get_auth0_user_id_from_request(request):
token = request.META.get('HTTP_AUTHORIZATION', '').split()[1]
payload = jwt_decode_handler(token)
return payload.get('sub')
17 changes: 17 additions & 0 deletions django/todoapi/views.py
Expand Up @@ -3,13 +3,30 @@

from rest_framework import generics

from .utils import get_auth0_user_id_from_request

# Lists and Creates entries of Task.
class TaskList(generics.ListCreateAPIView):
"""
Lists and creates tasks.
"""
queryset = Task.objects.all()
serializer_class = TaskSerializer

def perform_create(self, serializer):
auth0_user_id = get_auth0_user_id_from_request(self.request)
# Set the user to the one in the token.
serializer.save(created_by=auth0_user_id)

def get_queryset(self):
"""
This view should return a list of all Tasks
for the currently authenticated user.
"""
auth0_user_id = get_auth0_user_id_from_request(self.request)
return Task.objects.filter(created_by=auth0_user_id)

# Return a single Task and allows its update and deletion.
class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Returns a single Task and allows updates and deletion of a Task.
Expand Down

0 comments on commit c0d46c1

Please sign in to comment.