1. Create a Facebook Application by using your ‘Facebook Developer account’
2. Get the ‘App ID’ and ‘App Secret’ of your created application
Add following gems to your Gemfile
- 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 facebook_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" %>