Step 1:
Add gem into gemfile
gem 'omniauth-facebook'
Step 2:
Facebook App setup
https://developers.facebook.com/
Step 3:
run command on terminal
bundle install
Step 4:
Need to add facebook app id and facebook secret key
config/initializers/devise.rb
config.omniauth :facebook, 'facebook app id', 'facebook app secret',{:scope => 'email'}
Step 5:
we will need to create a User model to store our information that Facebook returns. Run the commands below to create the user model.
rails g model user provider uid name oauth_token oauth_expires_at:datetime
rake db:migrate
Step 6:
create omniauth_callbacks_controller
devise/omniauth_callbacks_controller.rb
class Devise::OmniauthCallbacksController < ApplicationController
skip_before_filter :authenticate_user!
def facebook
begin
@user = User.from_facebook_omniauth(request.env['omniauth.auth'])
session[:user_id] = @user.id
sign_in @user
flash[:success] = "Welcome, #{@user.name}!"
rescue
flash[:warning] = "There was an error while trying to authenticate you..."
end
redirect_to users_path
end
def failure
redirect_to root_path
end
end
Step 7:
config/routes.rb
devise_for :users, :controllers => {:omniauth_callbacks => "devise/omniauth_callbacks",registrations:"devise/registrations"}
Step 8:
Write a method in user model
app/model/user.rb
def self.from_facebook_omniauth(auth)
email = auth.info.email.present? ? auth.info.email : "#{auth.uid}@facebook.com"
user_exist = User.find_by_email(email)
if user_exist.nil?
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.email = email
user.first_name = auth.info.name.split(' ')[0]
user.last_name = auth.info.name.split(' ')[1]
user.username = auth.info.name.split(' ')[0].downcase
user.password = Devise.friendly_token[0,20]
end
else
user_exist.update(provider: auth.provider, access_token: auth.credentials.token, uid: auth.uid, first_name: auth.info.name, last_name: nil)
end
user_exist = User.find_by_email(email)
end