Пример #1
0
    def post(self, request):
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')

        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)

            # check token against facebook
            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)

            # add or update the user into users table
            ret = complete_social_login(request, login)

            # if we get here we've succeeded
            return Response(status=200, data={
                'success': True,
                'username': request.user.username,
                'user_id': request.user.pk,
            })

        except:

            return Response(status=401 ,data={
                'success': False,
                'reason': "Bad Access Token",
            })
Пример #2
0
    def post(self, request):
        print "posting data"
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')

        try:
            print request
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)

            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            print login
            ret = complete_social_login(request, login)
            return Response(status=200,
                            data={
                                'success': True,
                                'username': request.user.username,
                                'user_id': request.user.pk,
                            })
        except:
            return Response(status=401,
                            data={
                                'success': False,
                                'reason': "Bad Access Token",
                            })
Пример #3
0
 def get_sociallogin(self, request, data):
     app = SocialApp.objects.get(provider='facebook')
     fb_auth_token = SocialToken(app=app, token=data['token']['token'])
     login = fb_complete_login(request, app, fb_auth_token)
     login.token = fb_auth_token
     login.state = SocialLogin.state_from_request(request)
     return login
Пример #4
0
    def facebook_signup(self, request, access_token):
        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)

            fb_login = fb_complete_login(request, app, token)
            fb_login.token = token
            fb_login.state = SocialLogin.state_from_request(request)

            ret = complete_social_login(request, fb_login)

            response_data = {}

            if request.user.is_authenticated():
                if request.user.username == "":
                    request.user.username = request.data['email']
                    request.user.email = request.data['email']
                    request.user.first_name = request.data['fname']
                    request.user.last_name = request.data['lname']
                    request.user.save()
                data = UserProfileSerializer(request.user).data
                return data
            else:
                return {'error': "User with this email already exists."}
        except Exception as e:
            return {'error': str(e)}
Пример #5
0
 def post(self, request):  
      print "posting data"      
      data = JSONParser().parse(request)
      access_token = data.get('access_token', '')    
    
      try:
           print request
           app = SocialApp.objects.get(provider="facebook")
           token = SocialToken(app=app, token=access_token)
                        
           login = fb_complete_login(app, token)
           login.token = token
           login.state = SocialLogin.state_from_request(request)
           print login
           ret = complete_social_login(request, login)
           return Response(status=200, data={
            'success': True,
            'username': request.user.username,
            'user_id': request.user.pk,
        })
      except:
           return Response(status=401 ,data={
            'success': False,
            'reason': "Bad Access Token",
        })
Пример #6
0
def api_facebook_connect_by_token(request):
    ret = None
    if request.method == 'POST':
        form = FacebookConnectForm(request.POST)
        if form.is_valid():
            try:
                app = providers.registry.by_id(FacebookProvider.id)\
                .get_app(request)
                access_token = form.cleaned_data['access_token']
                token = SocialToken(app=app,
                    token=access_token)
                login = fb_complete_login(app, token)
                login.token = token
                login.state = SocialLogin.state_from_request(request)
                ret = complete_social_login(request, login)
            except:
                # FIXME: Catch only what is needed
                pass
    if not ret:
        raise Http404

    profile = Profile.objects.get_or_create(user=request.user)[0]
    profile.avatar_url = login.account.get_avatar_url()
    profile.save()
    user_source = UserResource()
    bundle = user_source.build_bundle(obj=request.user, request=request)
    bundle = user_source.full_dehydrate(bundle)
    bundle = user_source.alter_detail_data_to_serialize(request, bundle)
    return user_source.create_response(request, bundle)
Пример #7
0
        def post(self, request, provider=None, params=None, **kwargs):
            from requests import RequestException
            from allauth.socialaccount import providers
            from allauth.socialaccount.helpers import complete_social_login
            from allauth.socialaccount.models import SocialLogin, SocialToken
            from allauth.socialaccount.providers.facebook.provider import FacebookProvider

            if provider == 'facebook':
                try:
                    app = providers.registry.by_id(
                        FacebookProvider.id).get_app(request)
                    token = SocialToken(app=app, token=params.access_token)
                    login = fb_complete_login(request, app, token)
                    login.token = token
                    login.state = SocialLogin.state_from_request(request)
                    ret = complete_social_login(request, login)
                except RequestException:
                    return http.HttpBadRequest(
                        'Error accessing FB user profile')
                else:
                    # If user does not exist
                    if login.account.user.id is None:
                        return http.HttpBadRequest('Not registered')

                    return self._construct_login_response(login.account.user)

            return http.HttpBadRequest('Invalid provider')
Пример #8
0
    def save(self, request):
        user = self.validated_data['user']

        if user:
            return user
        else:
            app = SocialApp.objects.get(provider='facebook')
            social_token = SocialToken(app=app,
                                       token=self.validated_data['fcb_token'])

            try:
                # Check token against Facebook
                original_request = request._request
                login = fb_complete_login(original_request, app, social_token)
                login.token = social_token
                login.state = SocialLogin.state_from_request(original_request)
                complete_social_login(original_request, login)
            except HTTPError:
                # 400 Client Error
                raise exceptions.AuthenticationFailed(
                    _('Facebook authentication failed.'))
            else:
                self.cleaned_data = self.validated_data  # Needed by save_user()
                return get_socialaccount_adapter().save_user(
                    request, login, self)
Пример #9
0
    def post(self, request):
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')

        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)

            # check token against facebook
            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)

            # add or update the user into users table
            ret = complete_social_login(request, login)

            # if we get here we've succeeded
            return Response(status=200,
                            data={
                                'success': True,
                                'username': request.user.username,
                                'user_id': request.user.pk,
                            })

        except:

            return Response(status=401,
                            data={
                                'success': False,
                                'reason': "Bad Access Token",
                            })
Пример #10
0
def create_game(request):
    if request.method=="POST":
        lon=str(request.POST['longitude'])
        lat=str(request.POST['latitude'])
        access_token =str(request.POST['access_token'])
        type=str(request.POST['type'])
        #email=str(request.POST['email'])
        try:
            app=SocialApp.objects.get(provider="facebook")
            token=SocialToken(app=app,token=access_token)
             # Check token against facebook
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            # Add or update the user into users table
            ret = complete_social_login(request, login)
            a=SocialToken.objects.get(token=access_token)
            try:
                account=a.account
                user=account.user
                location = Point(lon, lat)
                game=Game.objects.create(host=user,location=location,type=type)
                return HttpResponse("done")
            except User.DoesNotExist:
                return HttpResponse("User Dosent Exist")
            return HttpResponse("wuhoo")
        except Exception as e:
            # If we get here we've failed
           return HttpResponse("ASdsa "+str(e))
Пример #11
0
    def post(self, request):        
        data = JSONParser().parse(request)
        access_token = data.get('access_token', '')    
        
        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)
                            
            # return SocialLogin(account)                    
            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
        
            # add or update the user
            ret = complete_social_login(request, login)

            # if we get here we've succeeded
            return Response(status=200, data={
                'success': True,
                'username': request.user.username,
                'user_id': request.user.pk,
                'csrf_token': unicode(csrf(request)['csrf_token'])
            })
            
        except:
            
            # FIXME: Catch only what is needed
            #, HttpForbidden
            return Response(status=401 ,data={
                'success': False,
                'reason': "Bad Access Token",
            })
Пример #12
0
def join_game(request):
    if request.method=="POST":
        id=str(request.POST['uuid'])
        access_token =str(request.POST['access_token'])
        type=str(request.POST['type'])
        #email=str(request.POST['email'])
        try:
            app=SocialApp.objects.get(provider="facebook")
            token=SocialToken(app=app,token=access_token)
             # Check token against facebook
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            # Add or update the user into users table
            ret = complete_social_login(request, login)
            a=SocialToken.objects.get(token=access_token)
            try:
                account=a.account
                user=account.user
                game=Game.objects.create(id=id)
                game.participants.add(user)
                return HttpResponse(serializers.serialize("json",[game]))
            except User.DoesNotExist:
                return HttpResponse("User Dosent Exist")
            return HttpResponse("wuhoo")
        except Exception as e:
            # If we get here we've failed
           return HttpResponse("ASdsa "+str(e))
Пример #13
0
def mobile_facebook_login(request):
    if request.method=="POST":
        response=HttpResponse
        access_token =str(request.POST['access_token'])
        #email=str(request.POST['email'])
        try:
            app=SocialApp.objects.get(provider="facebook")
            token=SocialToken(app=app,token=access_token)
             # Check token against facebook
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            # Add or update the user into users table
            ret = complete_social_login(request, login)
            a=SocialToken.objects.get(token=access_token)
            try:
                account=a.account
                user=account.user
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                profile=UserProfile.objects.get_or_create(user=user,dp=account.get_avatar_url(),fullName=user.get_full_name())[0]
                return HttpResponse(serializers.serialize("json",[profile]))
            except User.DoesNotExist:
                return HttpResponse("User Dosent Exist")
            return HttpResponse("wuhoo")
        except Exception as e:
            # If we get here we've failed
           return HttpResponse("ASdsa "+str(e))
Пример #14
0
    def post(self, Request):
        serializer = UserLoginSerializer(data=Request.data)
        if serializer.is_valid():
            request_data = serializer.data
            userId = request_data.get('fbuserId','')
            access_token = Request.data.get('access_token','')
            try:
                app = SocialApp.objects.get(provider="facebook")
                token = SocialToken(app=app,token=access_token)
                login = fb_complete_login(Request, app, token)
                login.token = token
                login.state = SocialLogin.state_from_request(Request)
                user = UserLogin.objects.all().filter(fbuserId = userId)
                # ret = complete_social_login(Request, login)

                if len(user) == 0:
                    serializer.save()
                    return Response(status=200 ,data={
                         'success': True,
                         'reason': "User created",
                         'data':user.values()

                    })
                else:
                    return Response(status=200 ,data={
                         'success': False,
                         'reason': "User already exist",
                         'data':user.values()
                     })
            except Exception,e:
                  return Response(status=400 ,data={
                         'success': False,
                         'reason':e,
                     })
Пример #15
0
        def post(self, request, provider=None, params=None, **kwargs):
            from requests import RequestException
            from allauth.socialaccount import providers
            from allauth.socialaccount.helpers import complete_social_login
            from allauth.socialaccount.models import SocialLogin, SocialToken
            from allauth.socialaccount.providers.facebook.provider import FacebookProvider

            if provider == 'facebook':
                try:
                    app = providers.registry.by_id(FacebookProvider.id).get_app(request)
                    token = SocialToken(app=app, token=params.access_token)
                    login = fb_complete_login(request, app, token)
                    login.token = token
                    login.state = SocialLogin.state_from_request(request)
                    ret = complete_social_login(request, login)
                except RequestException:
                    return http.HttpBadRequest('Error accessing FB user profile')
                else:
                    # If user does not exist
                    if login.account.user.id is None:
                        return http.HttpBadRequest('Not registered')

                    return self._construct_login_response(login.account.user)

            return http.HttpBadRequest('Invalid provider')
Пример #16
0
	def post (self,request):
		
		original_request = request._request
		data = JSONParser().parse(request)
		access_token = data.get('access_token', '')

		try:
			app = SocialApp.objects.get(provider='facebook')
			fb_auth_token = SocialToken(app=app, token=access_token)

			login = fb_complete_login(original_request, app, fb_auth_token)
			login.token = fb_auth_token
			login.state = SocialLogin.state_from_request(original_request)

			complete_social_login(original_request, login)
			token, _ = Token.objects.get_or_create(user=original_request.user)

			
			data_response ={
			'username': original_request.user.username,
			'objectId': original_request.user.pk,
			'firstName': original_request.user.first_name,
			'lastName': original_request.user.last_name,
			'email': original_request.user.email,
			'sessionToken': token.key,
			}
			return Response(status=status.HTTP_200_OK, data=data_response)
		except:
			return Response(status=status.HTTP_401_UNAUTHORIZED,data={
				'detail': 'Bad Access Token',
				})
Пример #17
0
    def post(self, request, format=None):
        """
        透過 Facebook access token 建立 Facebook 帳號或是登入
        """
        serializer = self.serializer_class(data=request.DATA)
        if serializer.is_valid():
            access_token = serializer.data.get('access_token')
            try:
                st = SocialToken.objects.get(token=access_token)
                user = st.account.user
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                if user.is_active:
                    login(request, user)

                serializer = UserInfoSerializer(request.user)
                return Response(serializer.data, status=status.HTTP_200_OK)
            except SocialToken.DoesNotExist:
                pass

            try:
                app = providers.registry.by_id(FacebookProvider.id).get_app(request)
                token = SocialToken(app=app, token=access_token)
                fb_login = fb_complete_login(request, app, token)

                complete_login(request, fb_login, app, token)
                serializer = UserInfoSerializer(request.user)
                return Response(serializer.data, status=status.HTTP_200_OK)
            except requests.RequestException as e:
                return Response(str(e), status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #18
0
    def post(self, request, format=None):
        """
        透過 Facebook access token 建立 Facebook 帳號或是登入
        """
        serializer = self.serializer_class(data=request.DATA)
        if serializer.is_valid():
            access_token = serializer.data.get('access_token')
            try:
                st = SocialToken.objects.get(token=access_token)
                user = st.account.user
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                if user.is_active:
                    login(request, user)

                serializer = UserInfoSerializer(request.user)
                return Response(serializer.data, status=status.HTTP_200_OK)
            except SocialToken.DoesNotExist:
                pass

            try:
                app = providers.registry.by_id(FacebookProvider.id).get_app(request)
                token = SocialToken(app=app, token=access_token)
                fb_login = fb_complete_login(request, app, token)

                complete_login(request, fb_login, app, token)
                serializer = UserInfoSerializer(request.user)
                return Response(serializer.data, status=status.HTTP_200_OK)
            except requests.RequestException as e:
                return Response(str(e), status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #19
0
 def social(self, request, access_token):
     app = SocialApp.objects.get(provider="facebook")
     token = SocialToken(app=app, token=access_token)
     login = fb_complete_login(request, app, token)
     login.token = token
     login.state = SocialLogin.state_from_request(request)
     complete_social_login(request, login)
     return (request, login.user)
Пример #20
0
    def facebook_login(self, request, **kwargs):
        """Facebook sign up using django allauth tastypie."""
        data = self.deserialize(
            request,
            request.body,
            format=request.META.get('CONTENT_TYPE', 'application/json'))

        if 'access_token' not in data:
            raise CustomBadRequest(
                code='missing_key',
                message='Must provide {missing_key} when login with facebook.'.format(missing_key='access_token'))

        # Assign the access_token
        access_token = data.get('access_token', '')

        # Import some modules necessary
        # from allauth.socialaccount import providers
        from allauth.socialaccount.models import (SocialLogin, SocialToken, SocialApp)
        from allauth.socialaccount.providers.facebook.views import fb_complete_login
        from allauth.socialaccount.helpers import complete_social_login, complete_social_signup
        from allauth.socialaccount import providers
        from allauth.socialaccount.providers.facebook.provider import FacebookProvider, GRAPH_API_URL

        try:
            app = SocialApp.objects.get(provider='facebook')

            token = SocialToken(app=app, token=access_token)

            provider = providers.registry.by_id(FacebookProvider.id)
            print(provider.get_fields())
            print(GRAPH_API_URL)

            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)

            ret = complete_social_signup(request, login)
            print(ret)
            # If we get here we've succeeded
            return self.create_response(
                request,
                {
                    'success': True,
                    'user_id': request.user.pk,
                    'username': request.user.username,
                })
        except Exception as ex:
            print(ex)
            raise CustomBadRequest(
                code="missing_key",
                message="Can't login.")
Пример #21
0
    def _wrapped_view(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)

        access_token = request.REQUEST.get('access_token', '')
        try:
            app = SocialApp.objects.get(provider='facebook')
            token = SocialToken(app=app, token=access_token)
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            complete_social_login(request, login)
            return view_func(request, *args, **kwargs)
        # TODO: what to except here?
        except:
            context = {'error': 'Unable to get or create facebook user.'}
            return render_response(request, 'assassin/login.html', context)
Пример #22
0
    def _wrapped_view(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)

        access_token = request.REQUEST.get('access_token', '')
        try:
            app = SocialApp.objects.get(provider='facebook')
            token = SocialToken(app=app, token=access_token)
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            complete_social_login(request, login)
            return view_func(request, *args, **kwargs)
        # TODO: what to except here?
        except:
            context = {'error': 'Unable to get or create facebook user.'}
            return render_response(request, 'assassin/login.html', context)
Пример #23
0
    def get(self, request, *args, **kwargs):
        request.encoding = "utf-8"

        try:
            original_request = request._request
            auth_token = request.GET.get('auth_token', '')

            # Find the token matching the passed Auth token
            app = SocialApp.objects.get(provider='facebook')
            fb_auth_token = SocialToken(app=app, token=auth_token)

            # check token against facebook
            login = fb_complete_login(original_request, app, fb_auth_token)
            login.token = fb_auth_token
            login.state = SocialLogin.state_from_request(original_request)

            # add or update the user into users table
            complete_social_login(original_request, login)
            # Create or fetch the session id for this user
            token, _ = Token.objects.get_or_create(user=original_request.user)
            # if we get here we've succeeded
            data = {
                'username': original_request.user.username,
                'objectId': original_request.user.pk,
                'firstName': original_request.user.first_name,
                'lastName': original_request.user.last_name,
                'sessionToken': token.key,
                'email': original_request.user.email,
            }

            print(data)

            return Response(
                status=200,
                data=data
            )

        except:
            traceback.print_exc(file=sys.stdout)
            return Response(status=401, data={
                'detail': 'Bad Access Token',
            })
Пример #24
0
    def login(self, request):
        try:
            original_request = request._request
            token = request.POST.get(self.token_key, '')

            google_auth_adapter = GoogleOAuth2Adapter(request=original_request)

            app = SocialApp.objects.get(provider=self.provider)
            social_auth_token = SocialToken(app=app, token=token)
            login = google_auth_adapter.complete_login(request=original_request, app=app, token=social_auth_token) \
                if self.provider is 'google' else fb_complete_login(request=request, app=app, token=social_auth_token)

            extra_data = login.account.extra_data
            json_error_response = None

            if 'email' not in extra_data:
                json_error_response = JsonResponse(
                    dict(message='email is not provided'), status=400)

            if json_error_response is not None:
                return json_error_response

            user = User.objects.filter(email=extra_data['email']).first()

            if user is not None:
                token, is_created = Token.objects.get_or_create(user=user)
                return JsonResponse(dict(key=token.key))

            login.token = social_auth_token
            login.state = SocialLogin.state_from_request(original_request)

            complete_social_login(original_request, login)
            token, is_created = Token.objects.get_or_create(
                user=original_request.user)

            return JsonResponse(dict(key=token.key))
        except HTTPError as e:
            return JsonResponse(dict(message=str(e)), status=400)
Пример #25
0
def mobile_facebook_login(request):
	response = HttpResponse() ## Create an HTTP Response Object
	if request.method == "POST": # The method better be a POST
		access_token = request.POST.get('access_token') # Get token
		email = request.POST.get('email') # Get email
		try:
			app = SocialApp.objects.get(provider="facebook")
			token = SocialToken(app=app, token=access_token)
			# Check token against facebook                  
			login = fb_complete_login(request, app, token)
			login.token = token
			login.state = SocialLogin.state_from_request(request)
			# Add or update the user into users table
			ret = complete_social_login(request, login)
			# Try to get username from email
			try:
				user = User.objects.get(email=email) # Get User
				# Login the user from Django's perspective
				user.backend = 'django_tours.auth_backend.PasswordlessAuthBackend'
				user = authenticate(email=user.email)
				auth_login(request,user)
                #request.session.cycle_key()
				# If we get here we've failed
			except:
				response['Auth-Response'] = 'failure: %s'%(e)
				response.status_code = 401 # Set status
				return response
			# If we get here we've succeeded
			response['Auth-Response'] = 'success'
			response['User-Is-Authenticated'] = '%s'%(request.user.is_authenticated())
			response.status_code = 200 # Set status  
			return response   
		except Exception,e:
			# If we get here we've failed
			response['Auth-Response'] = 'failure: %s'%(e)
			response.status_code = 401 # Set status
			return response
Пример #26
0
def mobile_facebook_login(request):
    if request.method == "POST":
        response = HttpResponse
        access_token = str(request.POST['access_token'])
        #email=str(request.POST['email'])
        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)
            # Check token against facebook
            login = fb_complete_login(request, app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            # Add or update the user into users table
            ret = complete_social_login(request, login)
            a = SocialToken.objects.get(token=access_token)
            try:
                account = a.account
                user = account.user
                tuple = UserProfile.objects.get_or_create(
                    user=user,
                    dp=account.get_avatar_url(),
                    fullName=user.get_full_name())

                if tuple[1] == True:
                    Token.objects.create(user=user)
                    UserProfile.objects.update(user=user, isNew=False)
                else:
                    UserProfile.objects.update(user=user, isNew=False)
                x = UserProfile.objects.filter(user=user).values('isNew')
                return JsonResponse({'results': list(x)})
            except User.DoesNotExist:
                return HttpResponse("User Dosent Exist")
            return HttpResponse("wuhoo")
        except Exception as e:
            # If we get here we've failed
            return HttpResponse(str(e) + "")
Пример #27
0
    def save(self, request):
        user = self.validated_data['user']

        if user:
            return user
        else:
            app = SocialApp.objects.get(provider='facebook')
            social_token = SocialToken(app=app, token=self.validated_data['fcb_token'])

            try:
                # Check token against Facebook
                original_request = request._request
                login = fb_complete_login(original_request, app, social_token)
                login.token = social_token
                login.state = SocialLogin.state_from_request(original_request)
                complete_social_login(original_request, login)
            except HTTPError:
                # 400 Client Error
                raise exceptions.AuthenticationFailed(
                    _('Facebook authentication failed.')
                )
            else:
                self.cleaned_data = self.validated_data  # Needed by save_user()
                return get_socialaccount_adapter().save_user(request, login, self)
Пример #28
0
    def facebook_login(self, request, **kwargs):
        self.method_check(request, allowed=['post'])

        data = self.deserialize(request,
                                request.raw_post_data,
                                format=request.META.get(
                                    'CONTENT_TYPE', 'application/json'))

        access_token = data.get('access_token', '')

        from allauth.socialaccount import providers
        from allauth.socialaccount.models import SocialLogin, SocialToken, SocialApp
        from allauth.socialaccount.providers.facebook.views import fb_complete_login
        from allauth.socialaccount.helpers import complete_social_login
        try:
            app = SocialApp.objects.get(provider="facebook")
            token = SocialToken(app=app, token=access_token)
            login = fb_complete_login(app, token)
            login.token = token
            login.state = SocialLogin.state_from_request(request)
            ret = complete_social_login(request, login)

            #if we get here we've succeeded
            return self.create_response(
                request, {
                    'success': True,
                    'username': request.user.username,
                    'user_id': request.user.pk,
                    'api_key': request.user.api_key.key,
                })
        except:
            # FIXME: Catch only what is needed
            return self.create_response(request, {
                'success': False,
                'reason': "Bad Access Token",
            }, HttpForbidden)