Access token from devise+omniauth-facebook authentication for using in fb-graph

humairatasnim picture humairatasnim · Apr 8, 2012 · Viewed 10.6k times · Source

I used devise and omniauth-facebook in my Rails 3 app for Facebook authentication, based on this tutorial: Adding Facebook auth to Rails 3.1 app, and it's working great!

But now I want to have full Facebook integration in my app, with which I can access the user's photos, friends, etc., and for that I am thinking of using fb_graph. fb_graph requires a token, and I wanted to know how to edit my user model to save the token and use it in fb_graph. Any help regarding this matter will be highly appreciated.

This is how my User model looks like right now:

class User < ActiveRecord::Base

# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :omniauthable

# Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :photos
  has_many :scrapbooks

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

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"]
      end
    end
  end
end

Answer

James Robey picture James Robey · Apr 11, 2012

You can do this:

User.create!(:email => data.email, :password => Devise.friendly_token[0,20], :authentication_token => access_token.credentials.token)

You will also need to add :authentication_token or whatever you named it to the attr_accessible