Utilizing Firebase login to integrate with Facebook API

My current setup involves Facebook authentication tied to login, all managed through Firebase. However, I now face the need to make an API call to Facebook using 'me/friends/' endpoint without having to send another request since I am already logged in.

To facilitate my connection to Facebook within Angular, I am utilizing the following wrapper: https://github.com/ccoenraets/OpenFB

Answer №1

No need for a wrapper. Utilize $firebaseAuth() along with $http() for seamless Graph API requests.

The Graph API is user-friendly and integrates smoothly with Firebase.

Ensure that you have granted the Facebook Friends permission; otherwise, you will not receive any data in return.

You can employ $firebaseAuth() to log in and acquire the Facebook access_token. This token can then be utilized with the Graph API for retrieving data via HTTP requests, which Angular simplifies through its $http library.

My coding style may differ, as I prefer following the guidelines of the Angular styleguide.

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', 'https://<my-firebase-app>.firebaseio.com/')
  .constant('FacebookAppId', '<app-id>')
  .service('RootRef', ['FirebaseUrl', Firebase])
  .factory('Auth', Auth)
  .factory('Friends', Friends)
  .controller('MainCtrl', MainCtrl);

function Friends($http, RootRef, $q, FacebookAppId) {

  function getFriends() {
    // Retrieve the currently logged-in user (could be null)
    var user = RootRef.getAuth();
    var deferred = $q.defer();
    var token = null;
    var endpoint = "https://graph.facebook.com/me/friends?access_token="

    // If no user is logged in, reject with an error and return the promise
    if (!user) {
      deferred.reject('error');
      return deferred.promise;
    } else {
      // User is present, retrieve the token
      token = user.facebook.accessToken;
      // Append the token to the endpoint
      endpoint = endpoint + token;
    }

    // Initiate the HTTP call
    $http.get(endpoint)
      .then(function(data) {
        deferred.resolve(data);
      })
      .catch(function(error) {
        deferred.reject(error);
      });

    // Return the promise
    return deferred.promise;
  }

  return {
    get: getFriends
  };
}
Friends.$inject = ['$http', 'RootRef', '$q', 'FacebookAppId'];

function Auth($firebaseAuth, RootRef) {
  return $firebaseAuth(RootRef);
}
Auth.$inject = ['FirebaseAuth', 'RootRef'];

function MainCtrl($scope, Friends) {

  $scope.login = function login() {
    Auth.$authWithOAuthPopup('facebook').then(function(authData) {
      console.log(authData, 'logged in!');
    });
  };

  $scope.getFriends = function getFriends() {
    Friends.get()
      .then(function(result) {
        console.log(result.data);
      });
  };

}
MainCtrl.$inject = ['$scope', 'Friends'];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() { var search = document.getElementById('search').value document.getElementById('results').innerHTML = "" console.log(search) var startIndex = I have a requirement to continuously make Ajax calls ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

When the user scrolls to the right side of the page, fresh content will be loaded

While there are many plugins available that enable content to be loaded when the user reaches the bottom of the page, I have been unable to find a jQuery plugin that allows content to be loaded when the user reaches the right side of the document. Does an ...

Check if a user is currently on the identical URL using PHP and JavaScript

In my Laravel and AngularJS project, I have a functionality where users can view and edit a report. I'm looking to add a feature that will prevent multiple users from editing the report at the same time - essentially locking it while one user is makin ...

Mastering Protractor: Implementing browser.sleep within element.all(locator).each(eachFunction)

I am currently expecting the text of each element to be printed one by one, followed by a sleep, and then the next element's text to be printed. However, what is actually happening is that all the texts are being printed first and then a single brows ...

Is there a way to determine the negative horizontal shift of text within an HTML input element when it exceeds the horizontal boundaries?

On my website, I have a standard HTML input field for text input. To track the horizontal position of a specific word continuously, I have implemented a method using an invisible <span> element to display the content of the input field and then utili ...

Encountering a "Token Error: Bad Request" when attempting to call the callback URL

Every time I try to invoke the callback URL with google-OAuth2, I encounter the following error: Error Traceback: TokenError: Bad Request at Strategy.OAuth2Strategy.parseErrorResponse (G:\projects\oauth\node_modules\passport-oauth ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

What could be the reason behind the disruption in this JavaScript associative array?

I'm facing an issue with my associative array, which I have confirmed through console.log to be initially: this.RegionsChecked = {"US":true,"APAC":true,"Canada":true,"France":true,"Germany":true,"India":true,"Japan":true,"LATAM":true,"MEA":true,"UK": ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

AngularJS data binding does not behave as intended when utilizing a service

I'm facing challenges with AngularJS services. As a beginner, there's probably something important that I'm overlooking here. The title {{p01g.visiteTitel}} is not updating automatically and continues to show "sometitle". The ng-repeat fun ...

Having trouble retrieving JSON with crossDomain jQuery AJAX

The process I followed was creating a rails 3.0 scaffold and exposing it using json, keeping it running. When accessing http://localhost:3001/objects.json I can view json data in the browser Next, I had a simple html file with code.jquery.com/jquery-1.7 ...

Issue with using async await in map function: async function may not complete before moving on to the next item in the

Currently, I have an array that needs to be mapped. Inside the mapping function, there is an asynchronous function being called, which conducts an asynchronous request and returns a promise using request-promise. My intention was for the first item in the ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

Protractor: Decrease the magnification

Currently, I am working with protractor and facing the challenge of zooming out to 50%. Despite trying numerous solutions found on StackOverflow, none have successfully resolved the issue. Some attempted solutions include: browser.actions().keyDown(protra ...