Facebook Integration in Rails3 using omniauth gem

Create a facebook Application by using your facebook developer account

Get the “App ID” and “App Secret” of your created application

Add following gems to your

gem ‘omniauth’
gem ‘omniauth-facebook’

Run bundle install

Create a middleware file named “omniauth.rb” in config/initializers path

Rails.application.config.middleware.use OmniAuth::Builder do

provider :facebook, ENV[‘FACEBOOK_KEY’], ENV[‘FACEBOOK_SECRET’],{:scope => ’email, read_stream, read_friendlists, friends_likes, friends_status, offline_access, publish_stream’}

end

This will hold the facebbok_app_key and facebook_secret_key with permissions

Set your custom callback url in routes

match ‘/auth/:provider/callback’, :to => ‘sessions#create’
match ‘/auth/failure’, :to => ‘sessions#failure’

Write the following codes in the Sessions Controller

def create
auth_hash = request.env[‘omniauth.auth’] # Got The precise information from facebook
if !auth_hash.nil?
@user = User.find_or_create_from_auth_hash(auth_hash)
self.current_user = @user
redirect_to ‘/’
end
end

def failure
flash[:notice] = “Sorry, but you didn’t allow access to our app!”
redirect_to ‘/’
end

Write the following code in your view page. You can use a custom image for the facebook like “facebook.png”.

<%=link_to image_tag(‘/images/facebook.png’),”/auth/facebook” %>

Advertisements