Devise, Omniauth and Facebook integration session error

大城市里の小女人 提交于 2019-11-28 08:49:42

You are using old tutorial version.

If you are using devise 2.0 or higher the steps are:

in your config/initializers/devise.rb

require "omniauth-facebook"
config.omniauth :facebook, "YOUR_APP_ID", "YOUR_APP_SECRET", :strategy_class => OmniAuth::Strategies::Facebook

You must install this gems:

gem 'omniauth'
gem 'omniauth-facebook'
gem 'oauth2'

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

in your routes.rb

devise_for :users,  :controllers => { :omniauth_callbacks => "users/omniauth_callbacks", :registrations => "registrations" } do

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

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!