How To Get User Information From Facebook To Rails Application?

With Facebook’s Graph API and the creation of the Open Graph protocol, it is now easier then ever before to read and write data from facebook to rails application and back to the “social graph”. Here’s a few of the possibilities:

  • You could turn your webpage into a fully-featured Facebook-like page, just like if you were inside Facebook.
  • You can give your users the ability to sign in with their Facebook credentials and customize their experience with parameters taken from their Facebook profiles.
  • You could add a Like button to every object in your page such as images, songs, articles, etc., and tell your users which friends of theirs have liked your content.

Steps to create application and fetch information

A facebook app_id, and api_secret_key is needed

go to the link

https://developers.facebook.com/apps

1. Create new app on facebook
  • Give app name(example: sample_app)

  • then we need to fill following information

  • App domain: localhost

  • website url: http://localhost/3000/

On the same page we can find App Id & App Secret . It looks like

App ID: 378271044441102

App Secret: 567772fd2bef4dda7a404b02r4567c758

2. Create Rails application

The following are the steps to create rails application

  • rails new facebook_app
  • sudo gem install fb_graph
  • add to Gemfilegem “fb_graph”
  • sudo bundle install
  • create index page to fb_loginrails generate controller pages index
  • set index to root page in config/routes.rbroot :to => “pages#home”
  • create authentication for app(simple authentication)
  • creating facebook controller and facebook model with :Identifier => string:access_token =>string
  • rails generate scaffold facebook identifier:string access_token:string
  • rails generate controller dashboard show
  • In pages controller redirect the page to dashboard:show if it is authenticated alreadycontroller/pages_controller.rb

def index

redirect_to dashboard_url if authenticated?

end

If not authenticated then root_path will be loaded ie. pages/index, create fb_login in this page to authebticate.

<% if authenticated? %>

<p><%= link_to “Logout”, facebook_path, :method => :delete %></p>

<% else %>

<fb:login-button length=”long” onlogin=”location.href = ‘<%= facebook_path %>'” scope=”<%=

Facebook.config[:scope] %>”> </fb:login-button>

<% end %>

3. Paste the following script code(for facebook login button)

<script src=”https://www.railscarma.com/wp-content/uploads/2013/02/all.js”></script>

<script>

FB.init({

appId: “<%= Facebook.config[:client_id] %>”,

cookie: true,

xfbml: true,

oauth: true,

status: true

});

</script>

<script type=”text/javascript”>

$(function () {

<% if flash[:error] %>

$.gritter.add({

title: “<%= flash[:error][:title] %>”,

text : “<%= flash[:error][:message] %>”,

image: “<%= flash[:error][:image] %>”,

time : 5000

});

<% elsif flash[:notice] %>

$.gritter.add({

title: “<%= flash[:notice][:title] %>”,

text : “<%= flash[:notice][:message] %>”,

image: “<%= flash[:notice][:image] %>”,

time : 3000

});

<% end %>

});

</script>

The above code is used to authenticate user through facebook, after authenticating user should redirect to dashboard url to show his information fetched from facebook. some facebook settings should be code in facebook model, and controller.

In controller/facebook_controller.rb.

before_filter :require_authentication, :only => :destroy

rescue_from Rack::OAuth2::Client::Error, :with => :oauth2_error

# handle Facebook Auth Cookie generated by JavaScript SDK

def show

auth = Facebook.auth.from_cookie(cookies)

authenticate Facebook.identify(auth.user)

redirect_to dashboard_url

end

# handle Normal OAuth flow: start

def new

client = Facebook.auth(callback_facebook_url).client

redirect_to client.authorization_uri(

:scope => Facebook.config[:scope]

)

end

# handle Normal OAuth flow: callback

def create

client = Facebook.auth(callback_facebook_url).client

client.authorization_code = params[:code]

access_token = client.access_token! :client_auth_body

user = FbGraph::User.me(access_token).fetch

authenticate Facebook.identify(user)

redirect_to dashboard_url

end

def destroy

unauthenticate

redirect_to root_url

end

private

def oauth2_error(e)

flash[:error] = {

:title => e.response[:error][:type],

:message => e.response[:error][:message]

}

redirect_to root_url

end

4. Paste this code in facebook.rb

def profile

@profile ||= FbGraph::User.me(self.access_token).fetch

end

class << self

extend ActiveSupport::Memoizable

def config

@config ||= if ENV[‘fb_client_id’] && ENV[‘fb_client_secret’] && ENV[‘fb_scope’] && ENV[‘fb_canvas_url’]

{

:client_id => ENV[‘fb_client_id’],

:client_secret => ENV[‘fb_client_secret’],

:scope => ENV[‘fb_scope’],

:canvas_url => ENV[‘fb_canvas_url’]

}

else

YAML.load_file(“#{Rails.root}/config/facebook.yml”)[Rails.env].symbolize_keys

end

rescue Errno::ENOENT => e

raise StandardError.new(“config/facebook.yml could not be loaded.”)

end

def app

FbGraph::Application.new config[:client_id], :secret => config[:client_secret]

end

def auth(redirect_uri = nil)

FbGraph::Auth.new config[:client_id], config[:client_secret], :redirect_uri => redirect_uri

end

def identify(fb_user)

_fb_user_ = find_or_initialize_by_identifier(fb_user.identifier.try(:to_s))

_fb_user_.access_token = fb_user.access_token.access_token

_fb_user_.save!

_fb_user_

end

end

Now we are ready to get user info if he authenticated, once he authenticate page will redirect to dashboard_url,

code in controller/dashboard_controller.rb

before_filter :require_authentication k

view for dashboard/show.html.erb

<h2>User Profile</h2>

<dl>

<dt>Username</dt>

<dd><%= current_user.profile.username %></dd>

<dt>Name</dt>

<dd><%= current_user.profile.name %></dd>

<dt>First Name</dt>

<dd><%= current_user.profile.first_name %></dd>

<dt>Middle Name</dt>

<dd><%= current_user.profile.middle_name %></dd>

<dt>Last Name</dt>

<dd><%= current_user.profile.last_name %></dd>

<dt>Gender</dt>

<dd><%= current_user.profile.gender %></dd>

<dt>Link</dt>

<dd><%= link_to current_user.profile.link, current_user.profile.link %></dd>

<dt>Email</dt>

<dd><%= current_user.profile.email %></dd>

<dt>About</dt>

<dd><%= current_user.profile.about %></dd>

<dt>Birthday</dt>

<dd><%= current_user.profile.birthday %></dd>

<dt>Work</dt></dl>

The above code is to show user information.

5. Finally create facebook.rb file in config

development: &defaults

client_id: “your facebook app_id”

client_secret: “facebook secret id”

scope: user_about_me,friends_about_me,user_activities,friends_activities,user_birthday,

friends_birthday,user_checkins,friends_checkins,user_education_history,

friends_education_history,user_events,friends_events,user_groups,friends_groups,

user_hometown,friends_hometown,user_interests,friends_interests,user_likes,friends_likes,

user_location,friends_location,user_notes,friends_notes,user_online_presence,

friends_online_presence,user_photo_video_tags,friends_photo_video_tags,user_photos

test:

<<: *defaults

production:

<<: *defaults

Get in touch with us.

Subscribe For Latest Updates

Related Posts

1 thought on “How To Get User Information From Facebook To Rails Application?”

  1. An impressive share! I’ve just forwarded this onto a colleague who has been conducting
    a little research on this. And he in fact bought me breakfast due to the fact
    that I stumbled upon it for him… lol. So let me reword
    this…. Thanks for the meal!! But yeah, thanks for spending some time to talk about this matter here on your blog.

Leave a Comment

Your email address will not be published. Required fields are marked *

en_USEnglish