Few days back I have to write an API to register a user using Facebook and Google social auth. The task was simple I will get facebook or google access_token in request and then I will use that to get User information from facebook and store it in Database and also create auth_token using django-rest-framework and return it in response so client side can use this token for subsequent calls.

The application was using django-social-auth for its web version already to give users the ability to register using Facebook and Google. The application was also using django-rest-framework version 2.4 for writing REST APIs.

The challenge was to use the same code for social authentication REST API. I searched this problem to see if there is already a solution available. I did not found the exact thing I was searching but this post Social Auth With Django Rest Framework helped me a lot. This post is using python-social-auth instead of django-social-auth and also using the django-rest-framework 3.0.

Assumptions:

I am assuming that you also have django-social-auth setup at web application level.

You have atleast beginner’s level Django knowledge and basic knowledge of Django Rest Framework.

urls.py


from django.conf.urls import patterns, include, url

urlpatterns += patterns(”,

url(r’^social-auth/$’, SocialSignUp.as_view({“post”: “create”, “get”: “list”}), name=’api-social-auth-register’),

)

 

Views.py

from django.contrib.auth import User

from social_auth.backends.google import GOOGLEAPIS_PROFILE, googleapis_profile
from rest_framework import status, mixins
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.throttling import AnonRateThrottle
from social_auth.backends import get_backend

from .serializers import UserRegisterSerializer

 

class SocialSignUp(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):

“””
Social Authentication API.
“””
permission_classes = (AllowAny,)
throttle_classes = (AnonRateThrottle, )

def create(self, request, *args, **kwargs):

“””
Create user using information from social channels like, facebook and google.

parameters:
– name: provider
description: provider can be facebook or google-oauth2
required: true
type: string
paramType: form
– name: access_token
description: Access Token which we will use to fetch the user’s detail.
required: true
type: string
paramType: form

parameters_strategy: replace
“””

redirect = request.path
try:

provider = request.DATA[‘provider’]
access_token = request.DATA[‘access_token’]

except KeyError:

return Response({‘success’: False, ‘detail’: “‘provider’ and ‘access_token’ are required parameters”},
status=status.HTTP_400_BAD_REQUEST)

backend = get_backend(provider, request, redirect)
request.social_auth_backend = backend

if access_token:

try:

if provider == “google-oauth2”:

test_response = googleapis_profile(GOOGLEAPIS_PROFILE, access_token)

if test_response is None:

return Response({‘success’: False, ‘detail’: “bad access_token”}, status=status.HTTP_400_BAD_REQUEST)

user = backend.do_auth(access_token, expires=None, *args, **kwargs)
my_user = User.objects.get(user=user)
user_serializer = UserRegisterSerializer(my_user)
return Response({‘success’: True, ‘detail’: user_serializer.data})

except Exception as e:

return Response({‘success’: False, ‘detail’: e},
status=status.HTTP_400_BAD_REQUEST)

 

serializers.py

from django.contrib.auth import User

from rest_framework import serializers
from rest_framework.authtoken.models import Token

class UserRegisterSerializer(serializers.ModelSerializer):

token = serializers.SerializerMethodField(‘get_user_token’)

def get_user_token(self, obj):

token, created = Token.objects.get_or_create(user=obj.user)
return token.key

class Meta:

model = User

About Author

[author] [author_image timthumb=’off’]https://media.licdn.com/mpr/mpr/shrinknp_200_200/p/6/000/22a/227/09063bb.jpg[/author_image] [author_info]Independent IT Consultant/Contractor, Technology student, enterprenuer and IT consultant, working hard to help people build scale able web and mobile applications. Muneeb Ahmad[/author_info] [/author]