diff --git a/notes/models.py b/notes/models.py index 00bd30a..a95ddd2 100644 --- a/notes/models.py +++ b/notes/models.py @@ -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): @@ -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) @@ -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) diff --git a/notes/urls.py b/notes/urls.py index ae35132..442d550 100644 --- a/notes/urls.py +++ b/notes/urls.py @@ -1,3 +1,4 @@ +from django.conf.urls import url from django.urls import path from .views import ( note_detail, @@ -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'), @@ -18,7 +17,5 @@ path('users/', 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()), ] diff --git a/notes/views.py b/notes/views.py index 46f99a9..3077e3e 100644 --- a/notes/views.py +++ b/notes/views.py @@ -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 @@ -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, + }) diff --git a/notes_api/settings/base.py b/notes_api/settings/base.py index 37d724b..5d47eb5 100644 --- a/notes_api/settings/base.py +++ b/notes_api/settings/base.py @@ -27,6 +27,7 @@ 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', + 'rest_framework.authtoken', 'notes', ] @@ -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', diff --git a/notes_api/settings/local.py b/notes_api/settings/local.py index c6c2556..9ebdf49 100644 --- a/notes_api/settings/local.py +++ b/notes_api/settings/local.py @@ -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', ) } diff --git a/notes_api/settings/production.py b/notes_api/settings/production.py index 24b75e6..5a402f2 100644 --- a/notes_api/settings/production.py +++ b/notes_api/settings/production.py @@ -10,7 +10,8 @@ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( - 'rest_framework.authentication.SessionAuthentication', + 'rest_framework.authentication.TokenAuthentication', + # 'rest_framework.authentication.SessionAuthentication', ) }