Skip to content

Instantly share code, notes, and snippets.

@jacobparra
Last active December 25, 2015 07:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobparra/6937991 to your computer and use it in GitHub Desktop.
Save jacobparra/6937991 to your computer and use it in GitHub Desktop.
Django AJAX Login using django-rest-framework
# -*- coding: utf-8 -*-
from rest_framework import serializers
from users import models
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField(max_length=254)
password = serializers.CharField(max_length=128)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ('id', 'email')
# -*- coding: utf-8 -*-
from django.contrib.auth import authenticate, login
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from users import serializers
class Login(APIView):
@method_decorator(csrf_protect)
@method_decorator(never_cache)
@method_decorator(sensitive_post_parameters('password'))
def post(self, request, *args, **kwargs):
credentials = serializers.LoginSerializer(data=request.DATA)
if not credentials.is_valid():
return Response(status=status.HTTP_400_BAD_REQUEST)
user = authenticate(username=credentials.object['email'],
password=credentials.object['password'])
if not user:
return Response(status=status.HTTP_401_UNAUTHORIZED)
# Okay, security check complete. Log the user in.
login(request, user)
serializer = serializers.UserSerializer(user)
return Response(serializer.data, status=status.HTTP_200_OK)
@kannor
Copy link

kannor commented Jul 7, 2014

@method_decorator(sensitive_post_parameters('password'))
Does not work well since the request object is not of type HttpRequest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment