用户没有使用Devise Omniauth Facebook添加到数据库

时间:2017-05-01 10:09:52

标签: ruby-on-rails facebook devise omniauth omniauth-facebook

我在我的网站中包含了Devise用户身份验证,但它运行良好。我现在正在尝试添加Facebook身份验证。

我可以使用FB登录,并将用户重定向回我的网站。当我在FB设置中检查连接的应用程序时,我可以看到我的网站已列出。

问题是FB没有添加到我的用户表中。当我检查数据库时,提供者和uid字段是空白的,并且网站仍然要求用户登录。

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :validatable,
  has_many :comments

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable,  :omniauthable, :omniauth_providers => [:facebook]


  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
      user.name = auth.info.name   # assuming the user model has a name
      #user.image = auth.info.image # assuming the user model has an image
      # If you are using confirmable and the provider(s) you use validate emails,
      # uncomment the line below to skip the confirmation emails.
      user.skip_confirmation!
    end
  end

  def self.new_with_session(params, session)
      super.tap do |user|
          if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
              user.email = data["email"] if user.email.blank?
          end
      end
  end

end

回调控制器

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def facebook
  # You need to implement the method below in your model (e.g. app/models/user.rb)
  @user = User.from_omniauth(request.env["omniauth.auth"])

  if @user.persisted?
    sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
    set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
  else
    session["devise.facebook_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
end

def failure
  redirect_to root_path
end

的routes.rb

#authentication
  devise_for :users, path: "auth", controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations',
    unlocks: 'users/unlocks',
    omniauth_callbacks: 'users/omniauth_callbacks'
  }

用户会话控制器

class Users::SessionsController < Devise::SessionsController
respond_to :js
before_action :configure_permitted_parameters, :if => :devise_controller?


  protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_in_params
    devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  end
end

devise.rb

     config.omniauth :facebook, '******', '*************', scope: "email", info_fields: 'email'

更新 刚刚发现我的用户表中有fname和lname字段,因此调整了user.rb以反映:

user.fname = auth.info.fname

0 个答案:

没有答案