Skip to content

Commit

Permalink
[backend] token authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
mark-graciov committed Jul 19, 2018
1 parent 92cb2e6 commit 954a978
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 41 deletions.
11 changes: 10 additions & 1 deletion notes/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token


class GGITUser(AbstractUser):
Expand All @@ -9,6 +12,12 @@ def __str__(self):
return '{}'.format(self.username)


@receiver(post_save, sender=GGITUser)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)


class Note(models.Model):
created_date = models.DateField(auto_now_add=True)
modified_date = models.DateField(auto_now=True)
Expand Down Expand Up @@ -38,4 +47,4 @@ class Comment(models.Model):
note = models.ForeignKey(Note, related_name='comments', on_delete=models.CASCADE)

def __str__(self):
return '{}: {}'.format(self.author, self.content)
return '{}: {}'.format(self.author, self.content)
9 changes: 3 additions & 6 deletions notes/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.conf.urls import url
from django.urls import path
from .views import (
note_detail,
Expand All @@ -6,9 +7,7 @@
note_publish,
user_detail,
user_unique,
user_register,
user_login,
user_logout, ping)
user_register, CustomAuthToken)

urlpatterns = [
path('notes/', note_list, name='note_list'),
Expand All @@ -18,7 +17,5 @@
path('users/<int:user_id>', user_detail, name='user_detail'),
path('users/is-unique/', user_unique, name='user_is_unique'),
path('users/register/', user_register, name='user_register'),
path('auth/login/', user_login, name='user_login'),
path('auth/logout/', user_logout, name='user_logout'),
path('ping/', ping, name='ping'),
url(r'^api-token-auth/', CustomAuthToken.as_view()),
]
44 changes: 13 additions & 31 deletions notes/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
Expand Down Expand Up @@ -121,33 +121,15 @@ def user_register(request):
return Response(user.errors, status=400)


@api_view(['POST'])
def user_login(request):
if request.method == 'POST':
username = request.data['username']
password = request.data['password']

try:
user = GGITUser.objects.get(username=username)

if user.check_password(password):
auth_login(request, user)
serializer = UserSerializer(user)
return Response(serializer.data, status=200)
except GGITUser.DoesNotExist:
pass

return Response(status=400, data={'message': 'Username or password is incorrect.'})


@api_view(['POST'])
def user_logout(request):
if request.method == 'POST':
auth_logout(request)
return Response(status=200)

class CustomAuthToken(ObtainAuthToken):

@ensure_csrf_cookie
@api_view(['GET'])
def ping(request):
return Response(status=200)
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user': UserSerializer(user).data,
})
3 changes: 2 additions & 1 deletion notes_api/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'notes',
]

Expand All @@ -35,7 +36,7 @@
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
Expand Down
3 changes: 2 additions & 1 deletion notes_api/settings/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
)
}

3 changes: 2 additions & 1 deletion notes_api/settings/production.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
)
}

Expand Down

0 comments on commit 954a978

Please sign in to comment.