I am new to Rails and am installing my first app that integrates Facebook sign in / sign up. I followed Ryan Bates\' RailsCast videos that were posted here: https://stackov
You are using old tutorial version.
If you are using devise 2.0 or higher the steps are:
1º in your config/initializers/devise.rb
require "omniauth-facebook"
config.omniauth :facebook, "YOUR_APP_ID", "YOUR_APP_SECRET", :strategy_class => OmniAuth::Strategies::Facebook
2º You must install this gems:
gem 'omniauth'
gem 'omniauth-facebook'
gem 'oauth2'
3º in you user.rb
model add module :omniauthable
sth like:
class User
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable, :omniauthable and :invitable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
end
4º in your routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks", :registrations => "registrations" } do
5º Create a folder users
inside your controllers folder and after you must create a file in app/controllers/users/omniauth_callbacks_controller.rb
In this omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
# with this code you can see the data sent by facebook
omniauth = request.env["omniauth.auth"]
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
sign_in_and_redirect @user, :event => :authentication
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end
6º In your user.rb model add to the end this two methods:
def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(name:auth.extra.raw_info.name,
provider:auth.provider,
uid:auth.uid,
email:auth.info.email,
password:Devise.friendly_token[0,20]
)
end
user
end
def self.new_with_session(params, session)
super.tap do |user|
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["user_hash"]
user.email = data["email"]
end
end
end
7º Last you must add a link to connect with facebook:
In your devise/registrations/new.html.erb
you must add:
<%= link_to "Sign in with Facebook", user_omniauth_authorize_path(:facebook) %>
that's all. I hope that it will help! Regards