Search code examples
angularjsdjangodjango-rest-frameworkgoogle-signindjango-socialauth

how to make social login with DRF as backend and angularjs as frontend and DRF return jwt token for further interaction


I am using angularjs as frontend and djnago rest frame(DRF) as backend. I want to make social login for my site.

Requirements

  1. User logs in using the app to FB/Google.
  2. FB/Google returns an access_token.
  3. The app sends this access_token to Django backend using POST request.
  4. Django Backends find the user associated to this FB account or creates a new one using first name, last name and email from FB account.
  5. Django returns a JWT token for further authentication.
  6. The JWT is saved on the browser as cookies.
  7. Next the app uses this JWT to authenticate the user and then no more FB log in is necessary.

pls help me how i make this..


Solution

  • I recommend you use Sattelizer is an angulajs library to use JWT with social logins and here is an example with python (the example uses Flask but you can apply the same logic in django)

    I used this in django

    from rest_framework_jwt.settings import api_settings
    from rest_framework.views import APIView
    from rest_framework import status
    from rest_framework.response import Response
    from django.contrib.auth.models import User
    from django.shortcuts import get_object_or_404
    from modules.Pacientes.models import Paciente
    from modules.Doctores.models import Doctor
    from urllib.parse import parse_qs, parse_qsl
    from django.conf import settings
    import json
    import requests
    from .utils import *
    import uuid
    
    JWT_PAYLOAD = api_settings.JWT_PAYLOAD_HANDLER
    JWT_ENCODE = api_settings.JWT_ENCODE_HANDLER
    
    
    class AuthGoogle(APIView):
        def post(self, request):
    
            data = dict(client_id=request.data['clientId'],
                        redirect_uri=request.data['redirectUri'],
                        client_secret=settings.GOOGLE_SECRET,
                        code=request.data['code'],
                        grant_type='authorization_code')
            print(data)
            print(settings.ACCESS_TOKEN_URL)
            # Obteniendo Access Token
            r = requests.post(settings.ACCESS_TOKEN_URL, data=data)
            token = json.loads(r.text)
            print(token)
            headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}
    
            # Obteniendo datos de perfil
    
            r = requests.get(settings.PEOPLE_API_URL, headers=headers)
    
            profile = json.loads(r.text)
    
            print(profile['email'])
    
            try:
                user = User.objects.get(email=profile['email'])
            except User.DoesNotExist:
                user = None
    
            if user:
                payload = JWT_PAYLOAD(user)
                token = JWT_ENCODE(payload)
                return Response({'token': token}, status.HTTP_200_OK)
    
            else:
                user = User.objects.create_user(username=profile['given_name'], email=profile["email"], password="nexo2016")
                paciente = Paciente(user=user, pic_profile=profile['picture'], google_sub=profile['sub'])
                paciente.save()
                send_email_welcome(user)
                payload = JWT_PAYLOAD(user)
                token = JWT_ENCODE(payload)
                return Response({'token': token}, status.HTTP_201_CREATED)
    
    
    class AuthFacebook(APIView):
        def post(self, request):
    
            data = dict(client_id=request.data['clientId'],
                        redirect_uri=request.data['redirectUri'],
                        client_secret=settings.FACEBOOK_SECRET,
                        code=request.data['code'],
                        )
            r = requests.get(settings.ACCESS_TOKEN_URL_FACEBOOK, params=data)
            access_token = json.loads(r.text)
            print(r.text)
            r = requests.get(settings.GRAPH_API_URL, params=access_token)
            print(r.text)
            profile = json.loads(r.text)
    
            try:
                user = User.objects.get(email=profile['email'])
            except User.DoesNotExist:
                user = None
    
            if user:
                payload = JWT_PAYLOAD(user)
                token = JWT_ENCODE(payload)
                return Response({'token': token}, status.HTTP_200_OK)
            else:
                user = User.objects.create_user(username=profile['name'], email=profile['email'],
                                                first_name=profile['first_name'], last_name=profile['last_name'])
                paciente = Paciente(user=user,
                                    pic_profile='https://graph.facebook.com/' + profile['id'] + '/picture?type=normal',
                                    facebook_id=profile['id'])
                paciente.save()
                send_email_welcome(user)
                payload = JWT_PAYLOAD(user)
                token = JWT_ENCODE(payload)
                return Response({'token': token}, status.HTTP_201_CREATED)
    
            return Response(request.data, status.HTTP_500_INTERNAL_SERVER_ERROR)
    

    I hope this could help you