Table of Contents
A 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 the 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.
Django Social Auth Integration With Django Rest Framework
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:</pre>
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)
Looking to hire a Django/python Development team
Share the details of your request and we will provide you with a full-cycle team under one roof.
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
	