Tutorial for restful_authentication on Rails with Facebook Connect in 15 minutes

[Update (10 April 2010): we've edited the tutorial to bring it up to date with the current incarnations of Facebook Connect, Facebooker and Rails.]

Back in June 2007 I wrote a popular tutorial on writing Facebook platform applications with Ruby On Rails. Time has moved on and Facebook has launched Facebook Connect which allows you to integrate Facebook into your own sites allowing authentication, registration, friend connecting, and Facebook feed posting in the context of your application. Mashable has a great post on 10 great implementations of Facebook Connect including Joost, Vimeo and Disqus.

At Made By Many we are fans of the possibilites of Facebook Connect for lowering barriers to registration, extracting social graph and injecting your social media functions into the daily online life of users. There is little point trying to create a “new” facebook on your site. Your unique social proposition lies elsewhere with your content, community and tools.

People have found the integration of Facebook Connect tricky and while great libraries like facebooker handle the API part, actually getting the profile linking and integration flow is harder. So I’ve written this tutorial to integrate the most commonly used starter plugin for authentication and registration in Ruby On Rails, restful_authentication, with Facebook Connect to allow your users to login and register through Connect.

First of all, let’s state what this integration is going to achieve:

  • As a user I can register to the site through entering my details so I can access all that great functionality
  • As a user I can login to the site through my entered username and password
  • As a user I can register to the site through Facebook Connect so I don’t have to fill in that form
  • As a user I can login to the site through Facebook Connect so I don’t have to remember two passwords
  • As a user I can connect my existing site user with my Facebook Connect user so I can later login through Facebook Connect

We also have a constraint we need to consider:

  • As a user if I register a user through entering my details and later login through Facebook Connect I want to make sure I retain my old user account

So read on and I’ll have you Connected in 15 minutes.

We will first create a standard restful_authentication Rails application. I’m going to user mysql for this example


rails -d mysql connect_tutorial
cd connect_tutorial

Then we need to install the restful authentication plugin:


cd vendor/plugins
git clone git://github.com/technoweenie/restful-authentication.git restful_authentication
cd ../..
./script/generate authenticated user sessions

Next, we create our database:


rake db:create
rake db:migrate

Now move include AuthenticatedSystem from the Sessions Controller to the Application Controller.

Start the server and browse to http://localhost:3000/signup. Bingo, Restful Authentication in 3 minutes. Don’t create any users yet we need to make to add some fields to connect up our accounts.

We need two extra columns for our users: one to store the Facebook user ID and another to store a special hash of our users email address which we can use to later match new Facebook users to existing accounts to take care of our constraint. Let’s create a migration for that:


script/generate migration add_users_fb

Edit the migration so that it looks like this:


def self.up
  add_column :users, :fb_user_id, :integer
  add_column :users, :email_hash, :string
  #if mysql
  execute("alter table users modify fb_user_id bigint")
end

def self.down
  remove_column :users, :fb_user_id
  remove_column :users, :email_hash
end

The ask Rake to run the migration:


rake db:migrate

For the Facebook heavy lifting, we are going to use the facebooker plugin. This will handle the API level communication for us.


script/plugin install git://github.com/mmangino/facebooker.git

You are now going to have to create a Facebook Application on Facebook to get your API key and secret. Head over to http://www.facebook.com/developers/createapp.php

picture-3

(Enter your own application name)

Facebook Connect setup screen

Take a note of the api_key and secret and add these to config/facebooker.yml. Also, make sure you set the callback_url to your local development server.


development:
  api_key: {YOUR_KEY}
  secret_key: {YOUR_SECRET}
  canvas_page_name:
  callback_url: http://localhost:3000/
  pretty_errors: true
  set_asset_host_to_callback_url: true
  tunnel:
    public_host_username:
    public_host:
    public_port: 4007
    local_port: 3000

Then, back at Facebook, select the Connect tab on the left of the page and enter your Connect URL (this used to be called the Callback URL) – for the purposes of this tutorial, you should set this to http://localhost:3000/ – make sure you include the trailing slash or Facebook’s form will complain:

fb-connect-screen-2

Now we need to create a cross-domain receiver file for Facebook Connect to callback on. Luckily, facebooker can do that for us, but make sure you have configured your facebooker.yml file correctly, or the generator will bomb out:


script/generate xd_receiver

We need to initialise the Facebook Connect on every page. This consists of 3 things:

  1. adding a namespace declaration for FBML
  2. adding the Facebook Connect Javascript
  3. initialising the Javascript

Luckily facebooker can do some of this for us, so we create a generic layout index.html.erb


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<%= javascript_include_tag :defaults%>
</head>
<body>
<%= fb_connect_javascript_tag %>
<%= init_fb_connect "XFBML"%>
<%=yield%>
</body>

And add the following to ApplicationController


layout 'index'
before_filter :set_facebook_session
helper_method :facebook_session

You are now ready to roll with some Facebook Connect tags. Add the following to the bottom of sessions/new.html.erb


<p>or login with Facebook connect</p>
<%= fb_login_button('window.location = "/users/link_user_accounts";')%>

And the following to users/new.html.erb


<p>or register with Facebook connect</p>
<%= fb_login_button('window.location = "/users/link_user_accounts";')%>

We also add another registration field for name


<p><%= label_tag 'name' %><br/>
<%= f.text_field :name %></p>

These are going to create FBML tags which the Facebook connect Javascript will render as our Connect buttons

Start (or restart) the server and go to http://localhost:3000/login. The result should look like the following screenshot. If not, retrace your steps to make sure you’ve not done something wrong.

picture-5

Now it’s time to integrate. We need to do three main things

  1. When you are logged in through a Facebook session then login through restful authentication
  2. Link accounts between Facebook and Restful Authentication
  3. Create accounts when someone login or register with facebook.

In order to do this, we first need to edit lib/authenticated_system.rb. Change the current_user method to:


def current_user
  @current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || login_from_fb) unless @current_user == false
end

Also, we need to add the following method:


def login_from_fb
  if facebook_session
    self.current_user = User.find_by_fb_user(facebook_session.user)
  end
end

This will handle the seamless login for us. Now we need to add to our User model as follows:


#find the user in the database, first by the facebook user id and if that fails through the email hash
def self.find_by_fb_user(fb_user)
  User.find_by_fb_user_id(fb_user.uid) || User.find_by_email_hash(fb_user.email_hashes)
end

#Take the data returned from facebook and create a new user from it.
#We don't get the email from Facebook and because a facebooker can only login through Connect we just generate a unique login name for them.
#If you were using username to display to people you might want to get them to select one after registering through Facebook Connect
def self.create_from_fb_connect(fb_user)
  new_facebooker = User.new(:name => fb_user.name, :login => "facebooker_#{fb_user.uid}", :password => "", :email => "")
  new_facebooker.fb_user_id = fb_user.uid.to_i
  #We need to save without validations
  new_facebooker.save(false)
  new_facebooker.register_user_to_fb
end

#We are going to connect this user object with a facebook id. But only ever one account.
def link_fb_connect(fb_user_id)
  unless fb_user_id.nil?
    #check for existing account
    existing_fb_user = User.find_by_fb_user_id(fb_user_id)
    #unlink the existing account
    unless existing_fb_user.nil?
      existing_fb_user.fb_user_id = nil
      existing_fb_user.save(false)
    end
    #link the new one
    self.fb_user_id = fb_user_id
    save(false)
  end
end

#The Facebook registers user method is going to send the users email hash and our account id to Facebook
#We need this so Facebook can find friends on our local application even if they have not connect through connect
#We hen use the email hash in the database to later identify a user from Facebook with a local user
def register_user_to_fb
  users = {:email => email, :account_id => id}
  Facebooker::User.register([users])
  self.email_hash = Facebooker::User.hash_email(email)
  save(false)
end
def facebook_user?
  return !fb_user_id.nil? && fb_user_id > 0
end

This allows authentication to look up users either from their stored Facebook ID, or a hash of their email address. It also adds methods for our creating and linking. After any user is created we need to register them we Facebook Connect so add to the User model


after_create :register_user_to_fb

In the previous view’s Facebook Connect login button we added an after login JavaScript callback. This is to link our accounts after a user has gone through the callback process. We need to add this to the user controller


def link_user_accounts
  if self.current_user.nil?
    #register with fb
    User.create_from_fb_connect(facebook_session.user)
  else
    #connect accounts
    self.current_user.link_fb_connect(facebook_session.user.id) unless self.current_user.fb_user_id == facebook_session.user.id
  end
  redirect_to '/'
end

Don’t forget to add a route for this, as follows (make sure you replace the existing route for :users)


map.resources :users, :collection => {:link_user_accounts => :get}

Finally we need to have somewhere to go after login. Let’s create a home page under Users controller users/home.html.erb


<% if logged_in? %>
<h2>You are logged in as <%= current_user.name %></h2>
<% if current_user.facebook_user? %>
<fb:profile-pic uid="<%= current_user.fb_user_id%>" facebook-logo="true" size="thumb" ></fb:profile-pic>
<p><a href="#" onclick='FB.Connect.logoutAndRedirect("/logout")'>Logout</a></p>
<% else %>
<p>why don't you connect with your facebook account</p>
<%= fb_login_button('window.location = "/users/link_user_accounts";')%>
<p><%= link_to 'Logout', logout_path%></p>
<% end %>
<% else %>
<h2>You are not logged in!</h2>
<p><%= link_to 'Signup', signup_path%> or <%= link_to 'Login', login_path%></p>
<% end %>

And map it to root and delete public/index.html


map.root :controller => "users", :action => "home"

And it’s done. Stop the clock. Start (or restart) the server and go to http://localhost:3000/login and press the big connect button

picture-9

Login with your Facebook account. Restful Authentication with Facebook Connect. Done!

picture-7

Hope this helps you guys. You can find more Facebook Connect documentation on the developer wiki. I’m hoping to add to this tutorial with posting to the feed and connecting with friends so follow me @stueccles on Twitter for updates. You can find the code for this tutorial at github.

About the author

Stuart is a technologist’s technologist and one of the founding partners at Made By Many. He also is a champion of fluid, Agile business structures and new disruptive business models for a disruptive age. Follow @stueccles on Twitter

  • Comments (135)

    1. Great tutorial, Thanks a lot!

    2. Thanks for this tutorial

      If you’re using a recent version of Rails, you don’ need the line: execute(”alter table users modify fb_user_id bigint”)
      You can just add :limit => 20 to your migration column definition

    3. When I click the connect button on the register page, I get this error, and I cannot figure it out. Any help?

      NoMethodError in UsersController#home

      undefined method `set_facebook_session’ for #

    4. I’m not able to get this working, is it possible you could email the source code to me, at brettbj.jackson+ror@gmail.com ?

    5. I even downloaded the source code, and I still get errors.

    6. HI Brett.

      Your first issue sounds like you don’t have facebooker installed.

      For the downloadable source, you do need to change config/facebooker.yml to have you own Facebook application key and secret.

      There was an issue with resful_authentication in the github source as a submodule but i’ve just commited it instead.

      Stuart

    7. Nice post, thanks !

    8. Thanks, very useful !

    9. Thank you for a timely and well-written article!

    10. I had to set_asset_host_to_callback_url: false in order to make it work

    11. Great tutorial! Just what I was looking for, this saved a ton of time.

    12. Nice tutorial. I’m having 2 problems though:

      * I get a NoMethodError in UsersController#link_user_accounts; Rails doesn’t seem to recognize “facebook_session”. I have facebooker installed and have successfully authenticated using the normal Facebook API methods.

      * The FB Connect login buttons aren’t rendering, because using the helpers causes this JavaScript error in Firebug:
      Element.observe is not a function:
      Element.observe(window,’load’, function() {
      FB_RequireFeatures(["XFBML"], function() {
      FB.Facebook.init(’6d5xxxxxxxxx’,'/xd_receiver.html’);
      });
      });

      Anyone know what might be wrong? Thanks!

    13. why do i get a 500 internal server error when it redirects to “link_user_accounts”? could i possibly get the code in a zip?

    14. Avishai.

      Make sure you have < %= javascript_include_tag :defaults%> in your layout and before_filter :set_facebook_session in your Application Controller.
      You should include
      include AuthenticatedSystem

      in your Application Controll after before_filter :set_facebook_session.

      If all else fails check out the code on Github http://github.com/madebymany/restful-authentication-facebook-connect-tutorial/tree/master

      • The button is not rendering even after following the suggestions listed above.

        Any other advice?

        FBook Connect Button
    15. many thanx for this very understandable helping tutorial.
      great job!!

      i encountered a strange problem with the facebooker-plugin, during following your tut:
      after creating the views for the login i started my server and tried to connect to http://localhost:3000/login/ i got this strange error:

      Status: 500 Internal Server Error Content-Type: text/html

      which is caused by the layout.erb in vendor/plugins/facebooker/templates/.
      This is easily corrected by renaming the file to layout.erb.erb, but what is wrong with my settings, that this crazy behaviour appears?

    16. The 500 Internal Server Error is an issue with recent rails and mongrel. It is being triggered by facebooker due to a bug in the code that determines the layout to use for ‘pretty errors’. See here for how to fix the server error:

      http://billkirtley.wordpress.com/2009/03/03/failsafe-handling-with-rails/

      And until facebooker is updated (they know about it so should be soon) set pretty_errors to false in the yml config file.

    17. Question for you about linking accounts. It seems to leave the existing user account in the system. That is, I signup via FB. Logout. Signin via restful auth. Link my accounts. There is now an orphaned user record. I want to make sure I haven’t missed something. Is this the expected behaviour?

    18. Hi Philip,

      Little confusing because if you signup using FB you shouldn’t then be able to signin with restful auth. You can then create a new account using restful auth though and try to link with the facebook account, it then actually moves over the linked account to the new one and leaves an orphaned record of the first. This is expected behaviour but in a production application you may want to merge them or inform the user.

    19. Unfortunately (as of 18. Mar) facebooker does not work with Rails 2.3. I hope this could be fixed soon.

    20. I’ve got facebooker integrated with my rails project, and can log in via facebook connect. But I’m having some trouble getting it to log out. I call the FB.Connect.logoutAndRedirect(”/logout”) method, and my own logout method is called. The session is reset, but the facebook_session keeps coming back from the dead.
      I think it’s because set_facebook_session rematerializes it using the cookie (in secure_with_cookies!). Is there something else I need to do to stop it from doing this?

      FWIW, it does work for me in the sample app… thanks.

    21. So it turns out that the problem was that the cookies weren’t being cleared. I’m not sure why they were being cleared in the sample app, but I suspect it’s because the sample uses cookie-based sessions, rather than database-backed sessions which is what my app uses. Anyway, my solution was to modify controller.rb to expose clear_fb_cookies!, and call it when logging out.

    22. I get the following error when trying to run this app,

      undefined method `second’ for ["window.location = \"/users/link_user_accounts\";"]:Array

      The error arises from
      vendor/plugins/facebooker/lib/facebooker/rails/helpers/fb_connect.rb:57:in `fb_login_button’

      Any ideas?

      Dan

    23. Sorted, was using rails 2.1.1. It only works with 2.2.2

    24. Further to what @Avishai said, I had a similar error conflict when I followed these instructions. In my case the problem was jQuery. You either have to get rid of jQuery or look into running jQuery in noConflict mode (http://docs.jquery.com/Using_jQuery_with_Other_Libraries) since it appears the Facebook JS requires Prototype.

      Hope that helps!

    25. Hi Michael

      Thanks for the tip but could you please elaborate more how to override this behaviour of jQuery or disable it?

      Andrew Kingsley
    26. Great tutorial. I have the connect_tutorial working fine.

      However, in my real app I keep getting the following error when I call User.create_from_fb_connect.

      undefined method `fb_user_id’ for :false:Symbol

      Has anybody else seen this problem?

      The link_fb_connect works fine for users who already registered through restful_authentication. Just can’t seem to create a new user.

    27. hmmmm i guess i found a bug the script couldnt locate prototype.js libararies and all other required ones too its nothing to do with jQuery. here is the server dump
      http://localhost:3000/login -> /signup//javascripts/application.js?1237422344127.0.0.1 – - [20/Mar/2009:09:13:19 GMT] “GET /login HTTP/1.1″ 200 2007
      - -> /login
      127.0.0.1 – - [20/Mar/2009:09:13:19 GMT] “GET /signup//javascripts/prototype.js?1237422344 HTTP/1.1″ 404 695
      http://localhost:3000/login -> /signup//javascripts/prototype.js?1237422344
      127.0.0.1 – - [20/Mar/2009:09:13:20 GMT] “GET /signup//javascripts/effects.js?1237422344 HTTP/1.1″ 404 693
      http://localhost:3000/login -> /signup//javascripts/effects.js?1237422344
      127.0.0.1 – - [20/Mar/2009:09:13:20 GMT] “GET /signup//javascripts/dragdrop.js?1237422344 HTTP/1.1″ 404 694
      http://localhost:3000/login -> /signup//javascripts/dragdrop.js?1237422344
      127.0.0.1 – - [20/Mar/2009:09:13:20 GMT] “GET /signup//javascripts/controls.js?1237422344 HTTP/1.1″ 404 694
      http://localhost:3000/login -> /signup//javascripts/controls.js?1237422344
      127.0.0.1 – - [20/Mar/2009:09:13:20 GMT] “GET /signup//javascripts/application.js?1237422344 HTTP/1.1″ 404 697
      http://localhost:3000/login -> /signup//javascripts/application.js?1237422344

      Andrew Kingsley
    28. Sorry for the previous post I assesed what I was doing wrong

      Andrew Kingsley
    29. You can actually use:

      @@@ruby

      add_column :users, :fb_user_id, :bigint

    30. well it wasn’t the fb_user_id column, i forgot to create database migration for ‘name’ while creating a field for it.
      I kept on getting NoMethod error after login and something like undefined method `name’ for #
      so in my case the following migration did the trick.

      def self.up
      add_column :users, :name, :string
      end

      def self.down
      remove_column(:users, :name)
      end

      Andrew Kingsley
    31. Hi. Can you advice, how can I post newsfeed through connect or get info about friends. Thanks

    32. One small note. During the “Install restful authentication” section, I believe you want to add a line to:

      cd vendor/plugins before you do the git

      Thanks for the great tutorial.

    33. Thanks so much for posting this detailed tutorial.

      I spent a lot of time trying to get fb connect to work with facebooker without success, before I found this article.

      Your instructions worked perfectly.

    34. I get this error on the canvas page:

      Missing template users/home.erb in view path app/views

      The file name is home.html.erb as per this tutorial. It doesn’t give this error on my server, only when accessed through Facebook.

    35. Worked perfectly for me… THANK YOU!!!

      Dustin Anderson
    36. Thanks so much for this example. I’ve learned a ton from it.

      I did notice a documentation bug (#1) and a code bug (#2).

      #1: on this web page, you have a call to register_user_to_fb, when that user was created from the fb_user data:
      def self.create_from_fb_connect(fb_user)
      new_facebooker.register_user_to_fb
      end

      In your source code (which I downloaded), that call is not made.

      Your source code is correct I assume, there is no reason to call register_user_to_fb.

      #2: for the bug, let’s assume the following use case: your user has never visited your site, and the user attempts to login via Facebook Connect.

      The user is created in the users table via the create_from_fb_connect method.

      However, you have this line of code in the User model:

      after_create :register_user_to_fb

      So the register_user_to_fb method is called after create_from_fb_connect.

      The problem with register_user_to_fb is that it assumes that we have the email, which we won’t if the user *only* logged in via Facebook Connect. So this line of code:

      self.email_hash = Facebooker::User.hash_email(email)

      is essentially doing this:

      self.email_hash = Facebooker::User.hash_email(”")

      and the hash email for a Facebook Connect user is always:
      0_d41d8cd98f00b204e9800998ecf8427e

      To fix that, I wrapped the body of the register_user_to_fb method with a test to make sure the email wasn’t blank/nil.

      Hope that makes sense.

      Thanks again for contributing this page to the community. I would have spent hours researching to figure out how to do what you have already provided.

      Cheers,
      Ed

    37. Thanks for a great tutorial!

      However, it fails in Safari 4. The logout pattern described above, and in the example-code fails to log out the user. The session is recreated after a few seconds (my guess – for as long as it takes to get a new one from FB) – and magically, the user is logged in (and in my case – redirected again).

      Firefox 3 does not display the same erratic behavior!

    38. I’m running Rails 2.2.2 and have two problems…

      before_filter :set_facebook_session fails but this hack seems to be a work-around…

      def facebook_session
      if session[:facebook_session]
      session[:facebook_session]
      elsif params[:fb_sig_user]
      set_facebook_session
      end
      end

      The other issue is that it fails with a undefined local variable or method `fb_connect_javascript_tag’

      Any ideas?

    39. can someone help instruct me through this process for a dolphin site? I would really appreciate it, i’m having a hard time following the tut. in-jazz@hotmail.com

    40. callback_url should not have ‘/’ otherwise it will generate url that rails cannot handle.

    41. Thanks for the great tutorial!

      One question, though: early on, you mention that we can’t get the facebooker’s email address. But then later in the method “register_user_to_fb”, it appears you have the email address and generate its hash. Where is this email address coming from?

    42. I found this tutorial really interesting, but I had one problem when running the final application. If I log in I get the following message when I go back to the root of the page.

      “Facebooker::Session::SessionExpired in Users#home”
      “Session key invalid or no longer valid” …

      I think I’m missing something, but I tried several times to follow the steps explained and nothing changed.

      I tried then to download the demo you gave us on github, but when running rake:migrate I get an error on the facebooker plugin.

      Thanks a lot!

      • hey, did you ever find the solution for the “Session key invalid or no longer valid” error?

    43. Thanks so much Stuart – right on the money.
      Kudos!

    44. Please note. ClickToFlash does not work with FBML. If you have it installed, test to see if the site works in Firefox, if it does: ClickToFlash is at fault.

      That bug just cost me ALOT of frustration.

    45. If you are using jRails and jQuery, it will only work if you specify js => :jquery in the options:

      init_fb_connect “XFBML”, :js => :jquery

    46. I’m also getting the problem with

      undefined local variable or method `fb_connect_javascript_tag’ for #

      It appears that the FbConnect helper is never loaded, and I can’t work out why. Surely you don’t need to require the helper file directly.

      I’m using Rails 2.3.2, any ideas on how to get this to work?

    47. Hi tried to use this tutorial for rails 2.3. Get as well a similar error-message like Andrea (27. April 2009), but already in action: link_user_accounts

      Facebooker::Session::SessionExpired in UsersController#link_user_accounts

      any ideas how to solve?

      Cheers — jerik

    48. works now. My fault was that I had specified two times “map.resources :user”. Removing one solved the problem.

      #map.resources :users
      map.resources :users, :collection => {:link_user_accounts => :get}

      Cheers — jerik

    49. thanks for the tutorial. very helpful.

      Has anyone tried writing controller tests for the fbconnect functionality? I can’t seem to figure out how to, and there seems to be a HUGE lack of info/documentation on the internet…

    50. hi, excellent tutorial, think i’m halfway to getting it to work with an old app that uses acts_as_authenticated but getting this error when i try to login:

      Facebooker::Session::MissingOrInvalidParameter in AccountController#link_user_accounts

      Invalid email hash specified.

      any ideas?

    51. It seems as if the registration field you add for ‘Name’ under the register with facebook connect doesn’t actually do anything at all. Is there a way to make this pass an email address that the user enters?

    52. Hi,
      i have used your tutorial for facebook integration. ihave done well , but i have struck with the error something like

      /vendor/plugins/facebooker/lib/facebooker.rb:54:in `[]=’: can’t convert Hash into String (TypeError)
      in the console.

      can you please help me in this regard.
      Thank you.

    53. Hi there.

      How do I make it so a User has more fields and where would I put the RESTful stuff to make all that happen and editable? I tried to do it myself but it did not work at all.

      Thanks

    54. It looks like Facebook’s application creation pages/forms have changed from your screenshots. The new application forms that facebook has are quite a bit more confusing. What does that simple old “Callback URL” correspond to in Facebook’s new forms? Thanks.

    55. Ok, I think I found the answer to my own question. In the updated Facebook create application pages, go to the “Connect” tab, and put that “Callback URL” in the “Connect URL” field. With that in place, I followed the rest of the tutorial, and everything worked fine. Thanks!

    56. Hey there, I had a problem running “script/generate xd_receiver” on ubuntu 9.04, rails 2.2.2.

      If anyone else encounters this issue:

      Problem was that I hadn’t installed curl libraries, and i was lacking the typhoeus gem–follow instructions at http://github.com/pauldix/typhoeus/tree/master to clear things up.

    57. Most of everything seems to be working okay–but I can’t see my FB pic when I sign in…anyone have any pointers?

      Is my facebooker.yml sheet filled out incorrectly? What is supposed to go in “callback_url”–I’m just running my local server, so should “callback_url” be http://localhost:3000?

    58. Thanks for the post.

      There is a small bug in the Logout functionality. It’s actually caused by the
      User.find_by_fb_user method.

      The problem happens if one registers to the site with the ’same’ email address as he uses to login to Facebook but does not ‘connect’,

      If the user is logged in to facebook, hitting ‘logout’ on the separate site will not work because the
      User.find_by_fb_user method will return a user as the email_hash matches.

    59. I am a beginner, and find it very tough to follow. Can you make the steps easier for beginners to follow please?

    60. Hi,
      I have trouble getting the recommendations working with jQuery instead of prototype. I even cloned the whole example from github, changed the app so that it uses jquery. The init was also changed:

      init_fb_connect “XFBML”, :js => “jquery”

      Still, not even the connect button does render.

      Has anybody else tried to get it to work with jQuery?

      Any ideas are appreciated!
      mat

    61. hi im following all the instructions above but when i load my site i get this error everytime…
      any ideas what could be wrong?

      undefined method `fb_login_button’

      i was facing some difficulties installing facebooker – later i isntalled the gem and copied the dir to vendors/plugins. that should do it right?

      any ideas?
      thanks

    62. Got an implementation of facebooker and Facebook Connect working on Merb thanks to this article. Life saver!

    63. Yeah i could get it to work with few changes here and there! great tutorial though.

    64. Hey, thanks a lot for the tutorial! Everything works really well, but I have been struggling with the scenerio where one logs into my site with their fb account, then goes to facebook, logs in and then logs out through facebook. The facebook_session is still valid and so it shows FB.Connect.logoutAndRediret(), but it does not work. Has anyone run into this problem? Any possible solutions?

    65. I have a question about passwords. I have a password validation in my user model that requires a 6+ character password. The password in the example above is simple “”. This means that a user can’t update their profile after registration without running into validation errors.

      Additionally, if a user’s password is saved as “”, doesn’t that open them up to some serious security risks? Someone could log into their account simply by entering their username. Correct?

      Any input on this would be awesome!

      mail@joncrawford.com

    66. Hi,

      Thank you so much for the great tutorial!

      I am not using restful_authentication, but most of what you describe via facebook connect should work.

      I am a noob, and I have two quick, simple questions.

      After facebook login popup window appears and I put in my facebook user id and password, it brings up my site inside the popup window again. All the sites I’ve seen would close the popup window after authentication was successful.

      Also, I do want a new user who authenticates through facebook choose his/her username and one additional parameter after successful authentication.

      So, if I want to close the popup window and redirect the user to pick a username after successful facebook authentication, how would I go about doing it? Do I need to specify “Post-Authorize Callback URL” in facebook application settings? Or just change “link_user_accounts” function in User controller?

      Thank you so much in advance!

      Regards,

    67. Facebooker and Facebook have changed a few things since this tutorial.

      1) You need to edit your facebook.yml file before you run ruby script/generate xd_receiver, or else you may run into errors. How to set up facebook.yml is explained further in the tutorial.

      2) Facebook no longer, at least for the time being, supports localhost web developing via iFrame. You have to publish to a server in order to connect with Facebook.

      I found this site:http://sentientmobile.com/jshaw/blog/post/2009/01/12/Developing-Facebook-app-on-your-local-machine.aspx kinda explains a way to develop on localhost. I still have yet to find a good clean way to do it.

    68. I followed this tutorial and had a problem where facebook_session was always returning nil. I fixed it by specifying “127.0.0.1:3000″ instead of “localhost:3000″ as the “Connect URL” setting on Facebook, and as the “callback_url” field in facebooker.yml. After making these changes, facebook_session no longer returns nil, and I can happily develop locally.

    69. Scratch that. Missed something stupid. I’ve been reading that you must now use a public host through which to develop Facebook Connect.

    70. I hope someone is still moderating this thread and can delete my previous two posts. After banging my head against the table for nearly 5 hours, I’ve discovered that you MUST have a trailing slash on your “Connect URL.” So while http://localhost:3000 won’t work, http://localhost:3000/ will. Argh!

    71. ah, no need to worry. Stuart loves comments and now he can brag about having nearly 80 on his blog post , which is by far more than what any of the rest of us have:)

    72. Hi can u guide how to publish message on my facebook friends profiles.

    73. I’m getting the following exception when I click the Connect button:

      Processing UsersController#link_user_accounts (for 127.0.0.1 at 2009-10-02 15:09:01) [GET]

      NoMethodError (You have a nil object when you didn’t expect it!
      The error occurred while evaluating nil.user):
      app/controllers/users_controller.rb:35:in `link_user_accounts’

      Apparently, the method facebook_session is not defined. Is this somehow related to Rails 2.3.2?

      • Hey Andrés,

        I am having the same problem – did you find a workaround so far? It only happens when the user is NOT logged in to facebook (has no cookies).

        Thanks, michael

    74. HI Stuart Grate Tutorial,

      I am facing logout problem.

      when I am logout then it’s show me “you are logout from both side ” message but
      after refresh page it’s showing as login but facebook session has clear(logout from facebook).

      I am trying second way

      I am calling restful logout method code below

      def destroy
      self.current_user.forget_me if logged_in?
      cookies.delete :auth_token
      clear_fb_cookies!
      reset_session
      redirect_to( ‘/’ )
      end

      In code I am calling clear_fb_cookies! .
      It’s work but only logout from my application not from facebook

      Please help…..

    75. Installed and works great! Thanks for the tutorial!

      One problem though:

      I want to be able to use the traditional:

      rather than
      Logout

      Is there a way to do this? I’m trying to do as few checks as to whether or not the user is a facebook_user or not. It just really makes my views MESSY.

    76. Thanks Stuart. Very helpful. However, in some cases facebook is not following the correct callback_url. I have it set to :

      callback_url = http://www.example.com/

      and the xd_receiver.html is sitting at document root (/public). For some reason sometimes facebook is requesting:

      http://www.example.com/?sessionid=somesessionid&sessionkeysomesessionkey&next_url=www.example.com/xd_receiver.html

      I have an app filter at the root so this is redirecting facebook to a login page.
      I am going to try to set up a specific route to get around this, but I thought i’d see if you had seen this and had any ideas. Thanks

    77. Nice tutorial, Thanks
      saved my time.

    78. Thanks,Really helpful .
      Good job.

    79. hello every one
      i had a problem regarding this tutorial.
      i went through every step and all went fine….
      but when i tried to sign up with facebook account it says my application is under construction…
      i tried all these in localhost:3000 and my facebooker.yml file configuration is as follows

      development:
      api_key: {MY_KEY}
      secret_key: {MY_SECRET}
      canvas_page_name: {my application name}
      callback_url: http://localhost:3000/
      pretty_errors: true
      set_asset_host_to_callback_url: true
      tunnel:
      public_host_username:
      public_host:
      public_port: 4007
      local_port: 3000

    80. I like the madebymany tutorials very much..
      i am loving it

    81. now the login via face book is successful
      how do i post my status to facebook?
      Any help

    82. Thanks a lot :)

      I get the following error after Logging in with Facebook, page

      http://localhost:3000/users/link_user_accounts

      ActiveRecord::StatementInvalid in UsersController#link_user_accounts

      Mysql::Error: Duplicate entry ‘facebooker_xxx’ for key ‘index_users_on_login’: INSERT INTO `users` (`name`, `salt`, `created_at`, `crypted_password`, `remember_token_expires_at`, `updated_at`, `fb_user_id`, `email_hash`, `remember_token`, `login`, `email`) VALUES(’Andreas Constantin Meyer’, NULL, ‘2009-12-26 15:30:05′, NULL, NULL, ‘2009-12-26 15:30:05′, 501911990, NULL, NULL, ‘facebooker_xxx’, ”)

    83. Thanks a lot! Now I have a rough idea on how this works

    84. Can u add your activities on your site to your Facebook News Feeds?

    85. Thanks for the post….
      But I am having problem regarding curl. When I create the user it gives me error like
      “Curl::Err::ConnectionFailedError in UsersController#create
      Couldn’t connect to server”

      Can any one help me out…..

    86. Hello,

      I am a complete newb… I really want to create a Facebook app, but I’m afraid I don’t follow much of what’s going on in your tutorial or how many things I would need to install on my computer to make this work. I’ve taken a couple of C++ classes, but I don’t have much other experience in programming. Please let me know if you think this is possible for me to learn and what resources might be useful to me.

      Thank you so much

    87. $ script/generate xd_receiver

      gave me an error “Facebooker::AdapterBase::UnableToLoadAdapter”

      I configured the config/facebooker.yml file and then re-ran the command to generate an xd_receiver and got the expected output…

      create public/xd_receiver.html
      create public/xd_receiver_ssl.html

      It might help to switch these sections of the tutorial around. Evidently there was an update to facebooker on 7/31/2009 that makes the new sequence of steps necessary.

    88. Hello, rake db:migrate worked, however, I’m getting:

      No route matches “/signup” with {:method=>:get, :canvas=>false}

    89. Here is the full error:

      ActionController::RoutingError (No route matches “/signup” with {:method=>:get, :canvas=>false}):

      Rendering /Users/username/projectname/vendor/plugins/facebooker/templates/layout.erb (200)

    90. This looks like it would be a great tutorial, but I can’t even get restful_authentication installed :( i follow the directions step-by-step and still get an error that authenticated is not a generator when I try to generate the scaffolds. Where exactly do I put the restful_authentication folder and/or do I put its data into my rails app folder directly?

    91. ‘extracting social graph’

      I’m not really sure that that is supposed to convey. This looked a promising article, but as soon as I hit ‘gobbledegook’ instead of clear, well-written English, and in the second paragraph, at that, it had the same effect as a slow-loading web page.

      I skipped the rest of the article down to the comments form and took a minute or so to write this. That I took the trouble is in respect of what looked to be interesting and good quality technical content. If clarity were added, and pseudo-socio-market-speak omitted, readers such as me would stay long enough to do justice to your work.

      It’s a shame.

    92. Æ!!

      Really good post!
      I’m having a problem with rails 2.3. I’m reading the Rails 2.3 release notes (http://guides.rubyonrails.org/2_3_release_notes.html) and there was a lot of changes about CGI::Session that probably broke the facebook gems (rfacebook and facebooker).

      Somebody having the same problem? Some Fix?

      Cheers,

      PotHix

    93. when i run the script, ruby script/generate xd_receiver
      i jst encountered this error. im working in windows platform. then also i run this script from app folder. i succesfully installed facebooker and i configured facebooker.yml as shown in the tutorial.
      plz help me as possible..

      c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_re
      quire’: no such file to load — json (MissingSourceFile)
      from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `re
      quire’
      from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_suppo
      rt/dependencies.rb:156:in `require’
      from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_suppo
      rt/dependencies.rb:521:in `new_constants_in’
      from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_suppo
      rt/dependencies.rb:156:in `require’
      from C:/Documents and Settings/Milin Paul/My Documents/Rails apps/connec
      t_tutorial/vendor/plugins/facebooker/lib/facebooker.rb:1
      from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `ge
      m_original_require’
      from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `re
      quire’
      from c:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_suppo
      rt/dependencies.rb:156:in `require’
      … 23 levels…
      from c:/ruby/lib/ruby/gems/1.8/gems/rails-2.3.5/lib/commands/generate.rb
      :1
      from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `ge
      m_original_require’
      from c:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `re
      quire’
      from script/generate:3

      • C:/application>ruby script/generate authenticated user sessions
        Ready to generate.
        ———————————————————————-
        Once finished, don’t forget to:

        - Add routes to these resources. In config/routes.rb, insert routes like:
        map.signup ‘/signup’, :controller => ‘users’, :action => ‘new’
        map.login ‘/login’, :controller => ’sessions’, :action => ‘new’
        map.logout ‘/logout’, :controller => ’sessions’, :action => ‘destroy’

        ———————————————————————-

        We’ve create a new site key in config/initializers/site_keys.rb. If you have existing user accounts their passwords will no longer work (see README). As always, keep this file safe but don’t post it in public.

        ———————————————————————-
        exists app/models/
        exists app/controllers/
        exists app/controllers/
        exists app/helpers/
        create app/views/sessions
        exists app/controllers/
        exists app/helpers/
        create app/views/users
        exists config/initializers
        exists test/functional/
        exists test/functional/
        exists test/unit/
        exists test/fixtures/
        create app/models/user.rb
        create app/controllers/sessions_controller.rb
        create app/controllers/users_controller.rb
        create lib/authenticated_system.rb
        No such file or directory – C:/application/lib/authe
        nticated_system.rb

        So, I can’t find the authenticated_system.rb file mentioned above…

        Authentication problem
    94. Hey,

      When i am pointing to /login am getting the following error-

      NoMethodError in SessionsController#new

      undefined method `set_facebook_session’

      I tried looking around for fix but couldn’t find out. What may be the problem?

      Mohamed Sanaulla
    95. Hy!

      Fantastic post!

      Still, I have a little issue when clicking the faceBook connect button. The thrown output is as follows:
      ——————————————————————————————————-
      Unknown action
      No action responded to show. Actions: create, create_facebook_session, create_facebook_session_with_secret, facebook_params, facebook_session, facebook_session_parameters, link_user_accounts, new, one_or_true, redirect_to, render_publisher_error, render_publisher_interface, render_publisher_response, set_facebook_session, top_redirect_to, wants_interface?, and zero_or_false
      ——————————————————————————————————-

      Thanks for the help!

    96. very useful, thanks

    97. Great tutorial. Thanx stuart.

    98. reading this post is waste of time

    99. Exactly what I was looking for, something to get me started. Quick and well explained. Thanks!

    100. # If you’re building a Facebook connect site,
      # change the value of set_asset_host_to_callback_url to false

    101. I’m not able to get this working, is it possible you could email the source code to me, email : ranjeetrajasekar@gmail.com?

    102. I followed this notes,but its not working.NO Error message nothing is being shown .
      Can you please send the source code to my mail id :swetha.anguluri@hotmail.com.

      I want to know one thing,i.e should application name in facebook and project name be same?

      You have given to copy some code into lib/authenticatedsystem , i unable to find where is it actually located?

      What should we give in canvas page name and callback url in facebook page and also in facebooker,yml?

      Thanks In Advance.

    103. I am getting the error while loading, please give the source code to try once again.

    104. What went wrong if we get the “We’re sorry, but something went wrong.” page on the step where we first connect to http://web1.tunnlr.com:11025/signup?

      Authentication problem
    105. Not sure how to fix this problem:

      C:/application>ruby script/server
      => Booting Mongrel
      => Rails 2.3.2 application starting on http://0.0.0.0:3000
      => Call with -d to detach
      => Ctrl-C to shutdown server
      ?[4;36;1mSQL (0.0ms)?[0m ?[0;1mSET NAMES 'utf8'?[0m
      ?[4;35;1mSQL (1.0ms)?[0m ?[0mSET SQL_AUTO_IS_NULL=0?[0m

      Processing ActionController::Base#index (for 127.0.0.1 at 2010-04-21 00:26:48) [GET]

      NameError (uninitialized constant ApplicationController::AuthenticatedSystem):
      app/controllers/application_controller.rb:5
      app/controllers/profiles_controller.rb:1

      Rendered rescues/_trace (114.0ms)
      Rendered rescues/_request_and_response (2.0ms)
      Rendering C:/application/vendor/plugins/facebooker/t
      emplates/layout.erb (200)
      /!\ FAILSAFE /!\ Wed Apr 21 00:26:49 -0700 2010
      Status: 500 Internal Server Error

      ActionView::TemplateError (Invalid argument – ./C:/application/vendor/plugins/facebooker/templates/layout.erb) in C:/application/vendor/plugins/facebooker/templates/layout.erb:

      Authentication problem
    106. My default CSS is getting changed to a plain white background page…
      Any Help?

    107. Great tutorial, everything works great. I’m having a problem with Facebook Connect automatically logging me in however. Here is how it happens:

      Let’s say at some point I Facebook Connected in my app, so it has created a User record for me.
      One day I go to facebook.com and log in straight from there. I then visit my app, and it has automatically logged me in! I don’t like this assumption that just because there is a Facebook session active, I want to log in to my app. I want it to log in ONLY AFTER I have hit the Facebook Connect button (that’s how most sites do it at least).

      What’s responsible for this automatic login? I’m assuming it’s the before_filter :set_facebook_session, but how can I fix this behavior?

      Thanks!

    108. im trying to add facebook login capabilities and found your tutorial to be exactly what i was looking for
      however im trying to use as gem and not plugin
      ive added require ‘tasks/facebooker’ to rakefile and changed set_asset_host_to_callback_url: false
      othere then that, ive followed your instructions very closely

      the problem i am having is i do not see a blue facebook connect button

      any ideas why not?

    109. Excellent…this is exactly what I need for http://www.wheedly.com

    110. Hello, I encountered this error.

      undefined method `set_facebook_session’ for #

      Facebooker::Controller isn’t being included when I trigger a debugger from my controller and print out the result of self.ancestors.

      Any ideas how to include Facebooker::Controller? by the way I used latest version of rails. I used rails 2.3.5.

      Thanks…

    111. Great tutorial, helped out a lot!

      I have a question: Can this give me access to the Facebook Graph APIs “for free”? Or do I have to separately authenticate with OAuth, even if the account is already connected? I’d like to be able to grab my users’ friends in one go with linking accounts, if possible.

    112. Absolutely awesome!
      I’m completely new to rails and have messed around with the standard scaffolding, Bort, hobo and others but always ended up feeling like I was wading through more stuff than I needed. I’m completely sold on the idea of my app supporting only FB Connect and this is ultra-lightweight.

      I think I’ll go ahead and strip out the code that allows non-FB signup and login next. I feel like I never again want to do any data management that I don’t have to and love the declarative approach that Rails offers.

    113. hello ni hao wo yong de facebook api

    114. wei shenme bu neng zai facebook shang xianshi ne ????

      ????
      ???

    115. hi I have published this comment to Facebook, but there is nothing in my facebook. Could you tell me why ? Many thanks.

    116. Thanks for the great tutorial.

      Do you happen to know how this fits in with Facebook’s javascript SDK (http://developers.facebook.com/docs/reference/javascript/)?

    117. the fb connect button is not rendering in chrome. anyone else have seeing this issue?

    118. If you’re getting strange javascript errors such as:
      ActionController::RoutingError (No route matches “/prototype.js” with {:method=>:get, :canvas=>false})

      Go to config/facebooker.yml and make sure your callback_url has NO TRAILING SLASHES!

      It must be:

      http://localhost:3000

      instead of:

      http://localhost:3000/

      Got this tip from this blogger: http://loganleger.com/rails-facebooker-double-slashes-resource-routes

    119. awesome and to the point tutorial. Just what I was looking for.

      you sir, are great!

    120. cool man ……..

      Nice tutorial…

      Thanks alot….

    121. Hey all.. :)

      To render facebook button;

      add these lines to your layout…

      *
      *

      and you need to include following script after login button (in sessions/new.html.erb file)

      FB.init(”YOUR_API_KEY_HERE”, “/xd_receiver.htm”);

      Cheers.. :)

      • Hi Osman,

        I am having the same issue, but I don’t think I got those lines that you told us to add. Could you re-post?

    122. Thank you so much. An excellent resource!

    123. Try layout.html.erb

  • Responses (12)

    1. health information…健康还是亚健康? » Blog Archive » Tutorial for restful_authentication on Rails with Facebook Connect

      [...] Facebook has launched Facebook Connect which allows you to integrate Facebook into your own sites Read More|||“What if you could send a drink from the Virgin website to your friend on the plane using [...]

    2. Turulcsirip - Nagy Bence

      [...] Connect + Rails tutorial két nap késéssel http://www.madebymany.co.uk/tutorial-for-restful_authentication-on-rails-with-facebook-connect-in-15... « előző | Nagy Bence — 2009. 02. 27. [...]

    3. Diigo’ the week (weekly) » The Bipeds’ Monitor

      [...] Made By Many » Blog Archive » Tutorial for restful_authentication on Rails with Facebook Connect i… [...]

    4. Announcing Facebook integration at Nostradamical.com | Nostradamical.com/blog

      [...] There is also a great tutorial on implementing Facebook Connect with Rails and Restful Authentication here at MadeByMany. [...]

    5. OAuth vs Facebook Connect « Travid’s Blog

      [...] following a tutorial session on how to use Facebook Connect and reading Facebook Connect vs Twitter Oauth, I realized that the [...]

    6. My daily readings 05/30/2009 « Strange Kite

      [...] Made By Many » Blog Archive » Tutorial for restful_authentication on Rails with Facebook Connect i… [...]

    7. How to integrate Facebook Connect with a Rails app « Yangtheman

      [...] looked on the web for a while, and found a great example by Stuart Eccles at Made by Many. It’s an awesome tutorial, but it’s for restful_authentication. I don’t use it, [...]

    8. Webbstrategi.se - Läsvärt 17 December - Webbstrategi.se

      [...] Sahlin shared Tutorial for restful_authentication on Rails with Facebook Connect in … — 16:41 via [...]

    9. Blog What I Made » Week Notes Week 86

      [...] Ruby libraries with no real consensus on which is best. I ended up using Facebooker and following this tutorial which pretty much sorted me out. Watch out for the bug on that page though, you need [...]

    10. Chris Barretto’s Blog

      [...] UPDATE: This article is a bit out of date now, I have now posted an article on Rails, resful_authentication and Facebook connect [...]

    11. Some good Ruby on Rails tutorials

      [...] Using Facebook Connect with Rails – by Stuart Eccles [...]

    12. Facebook, Linked In, Twitter authetication integration for Rails

      [...] restful_authentication for facebook (by Stuart Eccles) [...]

Leave a comment

Our latest tweets

Categories

Recent comments

  • James Higgs: At some level Kujau wanted the attention, and the same seems to be true of Manning if he is indeed t...
  • William Owen: Sara, you've asked lots of pertinent questions here but I think you’re really asking quite a lot of ...
  • Sara Williams: James, as much as I want to agree with you -- you are right a very good percentage of the time -- th...
  • James Higgs: There is a certain logic to this: people are unlikely to go through a great deal of effo...
  • Tim Malbon: I think we should remember that we are in Afghanistan because its leaders allowed it to be used as a...