from django.http import HttpRequest
from rest_framework import serializers
from requests.exceptions import HTTPError
from allauth.socialaccount.helpers import complete_social_login


class SocialLoginSerializer(serializers.Serializer):

    access_token = serializers.CharField(required=True)

    def validate(self, attrs):
        access_token = attrs.get('access_token')
        view = self.context.get('view')
        request = self.context.get('request')
        if not isinstance(request, HttpRequest):
            request = request._request

        if not view:
            raise serializers.ValidationError(
                'View is not defined, pass it as a context variable'
            )

        self.adapter_class = getattr(view, 'adapter_class', None)

        if not self.adapter_class:
            raise serializers.ValidationError('Define adapter_class in view')

        self.adapter = self.adapter_class()
        app = self.adapter.get_provider().get_app(request)
        token = self.adapter.parse_token({'access_token': access_token})
        token.app = app

        try:
            login = self.adapter.complete_login(request, app, token,
                                                response=access_token)

            login.token = token
            complete_social_login(request, login)
        except HTTPError:
            raise serializers.ValidationError('Incorrect value')

        if not login.is_existing:
            login.lookup()
            login.save(request, connect=True)
        attrs['user'] = login.account.user

        return attrs

@@ -174,16 +174,158 @@
 l_login%0A
+from django.core.urlresolvers import NoReverseMatch%0Afrom django.db.utils import IntegrityError%0Afrom django.contrib.auth import get_user_model%0A
 %0A%0Aclass 
@@ -1545,16 +1545,213 @@
 value')%0A
+        except NoReverseMatch:%0A            %22%22%22%0A            Here we catch because all_auth wants to send us to a signup form%0A            to enter a new email address%0A            %22%22%22%0A            pass
 %0A       
@@ -1804,16 +1804,37 @@
 ookup()%0A
+            try:%0A    
         
@@ -1871,16 +1871,548 @@
 t=True)%0A
+            except IntegrityError:%0A                %22%22%22%0A                here we catch the IntegrityError because there is already an%0A                user with the same email address.%0A                Therefore we save login.account on our own and relate it to the%0A                already registered user%0A                %22%22%22%0A                user = get_user_model().objects.get(%0A                    email=login.account.extra_data%5B'email'%5D%0A                )%0A                login.account.user = user%0A                login.account.save()%0A
         

allow connection of social accounts with same email address