Adam Carlile
Adam Carlile

Reputation: 416

Add friends from facebook with Rails 3 + OmniAuth + FBGraph

I'm currently trying to write an add friends step to our registration system, and I've been asked to implement something similar to the way foursquare works.

It pulls down your friends from Facebook, checks to see if any of them are already on the foursquare site, and then asks if you want to connect with them.

What is the best way to go about implementing this kind of functionality?

I have seen examples with the FB JS SDK, however I would prefer a more integrated approach.

Thanks Adam

Upvotes: 2

Views: 3071

Answers (1)

krakover
krakover

Reputation: 3029

The best way I found is using devise with oauth and the fb_graph gems (like specified here and here). I had an issue with the versions so my gemfile configuration looks like this:

gem 'devise', :git => 'git://github.com/plataformatec/devise.git'
gem 'omniauth', '>=0.2.0.beta'
gem 'oa-oauth', :require => 'omniauth/oauth'
gem 'fb_graph'

(my configuration is quite old - it's possible that devise latest branch now supports omniauth in a more out-of-the-box way).

my devise initializer:

config.omniauth :facebook_publish, "APP_ID", "APP_SECRET"

In your User model:

devise :omniauthable

and

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  data = access_token['extra']['user_hash']
  if user = User.find_by_email(data["email"])
    user
  else # Create a user with a stub password. 
    User.create(:email => data["email"], :password => Devise.friendly_token[0,20]) 
  end
end

In order to facebook connect - go to path:

user_omniauth_authorize_path(:facebook)

Basically that is all you need for the connection. In order to get the graph I now use:

 facebook_user = FbGraph::User.new('me', :access_token => access_token['credentials']['token']).fetch

And for the friends:

facebook_user.friends

And that's it. Hope it helps.

Upvotes: 3

Related Questions