katherine95

SocialLoginView

Mar 25th, 2019
7,481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.88 KB | None | 0 0
  1. from django.http import JsonResponse
  2. from rest_framework import generics, permissions, status, views
  3. from rest_framework.response import Response
  4. from requests.exceptions import HTTPError
  5.  
  6. from social_django.utils import load_strategy, load_backend
  7. from social_core.backends.oauth import BaseOAuth2
  8. from social_core.exceptions import MissingBackend, AuthTokenError, AuthForbidden
  9. from . import serializers
  10.  
  11. class SocialLoginView(generics.GenericAPIView):
  12.     """Log in using facebook"""
  13.     serializer_class = serializers.SocialSerializer
  14.     permission_classes = [permissions.AllowAny]
  15.  
  16.     def post(self, request):
  17.         """Authenticate user through the provider and access_token"""
  18.         serializer = self.serializer_class(data=request.data)
  19.         serializer.is_valid(raise_exception=True)
  20.         provider = serializer.data.get('provider', None)
  21.         strategy = load_strategy(request)
  22.  
  23.         try:
  24.             backend = load_backend(strategy=strategy, name=provider,
  25.             redirect_uri=None)
  26.  
  27.         except MissingBackend:
  28.             return Response({'error': 'Please provide a valid provider'},
  29.             status=status.HTTP_400_BAD_REQUEST)
  30.         try:
  31.             if isinstance(backend, BaseOAuth2):
  32.                 access_token = serializer.data.get('access_token')
  33.             user = backend.do_auth(access_token)
  34.         except HTTPError as error:
  35.             return Response({
  36.                 "error": {
  37.                     "access_token": "Invalid token",
  38.                     "details": str(error)
  39.                 }
  40.             }, status=status.HTTP_400_BAD_REQUEST)
  41.         except AuthTokenError as error:
  42.             return Response({
  43.                 "error": "Invalid credentials",
  44.                 "details": str(error)
  45.             }, status=status.HTTP_400_BAD_REQUEST)
  46.  
  47.         try:
  48.             authenticated_user = backend.do_auth(access_token, user=user)
  49.        
  50.         except HTTPError as error:
  51.             return Response({
  52.                 "error":"invalid token",
  53.                 "details": str(error)
  54.             }, status=status.HTTP_400_BAD_REQUEST)
  55.        
  56.         except AuthForbidden as error:
  57.             return Response({
  58.                 "error":"invalid token",
  59.                 "details": str(error)
  60.             }, status=status.HTTP_400_BAD_REQUEST)
  61.  
  62.         if authenticated_user and authenticated_user.is_active:
  63.             #generate JWT token
  64.             login(request, authenticated_user)
  65.             data={
  66.                 "token": jwt_encode_handler(
  67.                     jwt_payload_handler(user)
  68.                 )}
  69.             #customize the response to your needs
  70.             response = {
  71.                 "email": authenticated_user.email,
  72.                 "username": authenticated_user.username,
  73.                 "token": data.get('token')
  74.             }
  75.             return Response(status=status.HTTP_200_OK, data=response)
Advertisement
Add Comment
Please, Sign In to add comment