简体   繁体   English

使用Devise和Omniauth进行Rails 4 Facebook身份验证

[英]Rails 4 Facebook authentication with Devise and Omniauth

I'm trying to implement authentication from Facebook in my app, for a Customer model. 我正在尝试在我的应用程序中针对客户模型从Facebook实施身份验证。 I had already done an authentication for Customers with Devise. 我已经使用Devise对客户进行了身份验证。 I had followed this guide . 我遵循了本指南 In the initializer devise.rb I added this row: 在初始化程序devise.rb中,我添加了以下行:

config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], scope: "email"

This is my Customer model: 这是我的客户模型:

class Customer < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
     :recoverable, :rememberable, :trackable #, :validatable

validates_presence_of :name

validates_uniqueness_of :nickname

before_save :complete_nickname

def complete_nickname
  if !self.nickname?
    self.nickname = self.email
  end
end

def facebook
  identities.where( :provider => "facebook" ).first
end

def facebook_client
  @facebook_client ||= Facebook.client( access_token: facebook.accesstoken )
end
end

This is my Identity model, written as specified in the guide: 这是我的身份模型,按照指南中的规定编写:

class Identity < ActiveRecord::Base
  belongs_to :customer

  validates_presence_of :uid, :provider
  validates_uniqueness_of :uid, :scope => :provider

  def self.find_for_oauth(auth)
    identity = find_by(provider: auth.provider, uid: auth.uid)
    identity = create(uid: auth.uid, provider: auth.provider) if identity.nil?
    identity.accesstoken = auth.credentials.token
    identity.refreshtoken = auth.credentials.refresh_token
    identity.name = auth.info.name
    identity.email = auth.info.email
    identity.nickname = auth.info.name.gsub(/\s+/, "")
    identity.image = auth.info.image
    identity.phone = auth.info.phone
    identity.urls = (auth.info.urls || "").to_json
    identity.save
    identity
  end
end

This is my OmniauthCallbackController 这是我的OmniauthCallbackController

class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    generic_callback( 'facebook' )
  end

  def generic_callback( provider )
    @identity = Identity.find_for_oauth env["omniauth.auth"]

    @customer = @identity.customer || current_customer
    if @customer.nil?
      @customer = Customer.create( email: @identity.email || "", nickname: @identity.email || "" )
      @identity.update_attribute( :customer_id, @customer.id )
    end  

    if @customer.email.blank? && @identity.email
      @customer.update_attribute( :email, @identity.email)
    end

    if @customer.persisted?
      @identity.update_attribute( :customer_id, @customer.id )
      # This is because we've created the user manually, and Device expects a
      # FormUser class (with the validations)
      @customer = FormUser.find @customer.id
      sign_in_and_redirect @customer, event: :authentication
      set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?
      else
        session["devise.#{provider}_data"] = env["omniauth.auth"]
        redirect_to new_customer_registration_url
      end
    end
  end

When I click on Login in with Facebook I am not authenticated, and the app redirects me on the login form. 当我单击“使用Facebook登录”时,我未通过身份验证,该应用程序在登录表单上重定向了我。 On the server outuput I see that it tried to create a Customer, but then it fails and rollbacks: 在服务器输出上,我看到它试图创建一个Customer,但是随后失败并回滚:

  SQL (0.3ms)  UPDATE "identities" SET "accesstoken" = $1, "updated_at" = $2 WHERE "identities"."id" = $3  [["accesstoken", "CAABtFtDqAlwBAEFzpAtw2W2gUTLkpKbtjI4lqKibkIO5kyJSwNYK9TDzDG4NfEoq40oQdUzXxZADRZBwYy319KPobEU6378ULwQ3PtKT46EbEugs4eIdsQyfZC3S8yLIJoPW6uq7ZAF0AnEeepDvl97ajbazsmGsuP22rnK0G1zSTHzoBfPpGZAD4NkgW7Kp5r5TiLhxxEgZDZD"], ["updated_at", "2015-11-24 11:18:28.010402"], ["id", 2]]
  (65.7ms)  COMMIT
  (0.2ms)  BEGIN
  Customer Exists (4.0ms)  SELECT  1 AS one FROM "customers" WHERE  "customers"."nickname" = '' LIMIT 1
  (0.2ms)  ROLLBACK

Maybe it's a validation control that I already had on my Customer object, but I can't figure out what it can be. 也许这是我已经在我的Customer对象上使用的一个验证控件,但是我不知道它可以是什么。 This is the schema of my Customer: 这是我的客户的架构:

  create_table "customers", force: :cascade do |t|
    t.string   "email",                   default: "",   null: false
    t.string   "encrypted_password",      default: "",   null: false
    t.string   "name",                    default: "",   null: false
    t.string   "surname",                 default: "",   null: false
    t.string   "nickname",                default: "",   null: false
    ...
  end

Someone can help me? 有人可以帮我吗? Thanks in advance 提前致谢

Try to this configuration 尝试这种配置

devise.rb devise.rb

config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], scope: 'email', info_fields: 'email, name'

I solved, it seems to work with my Facebook account. 我解决了,似乎可以使用我的Facebook帐户。 I update the omniauth-facebook gem, that maybe was part of the issue, with bundle update omniauth-facebook . 我使用bundle update omniauth-facebook更新了omniauth-facebook gem,这也许是问题的一部分。 I modified the initializer devise.rb in this way (no spaces in scope and info_fields): 我以这种方式修改了初始化程序devise.rb(作用域和info_fields中没有空格):

`config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], scope: "email,public_profile", info_fields: 'email,name,first_name,last_name'`

And modified the OmniauthCallbackController: 并修改了OmniauthCallbackController:

@customer = Customer.create( email: @identity.email || "", nickname: @identity.nickname || "", 
  name: env["omniauth.auth"]["info"]["first_name"] || "", 
  surname: env["omniauth.auth"]["info"]["last_name"] || "",
  password: "********", password_confirmation: "********" )
  @identity.update_attribute( :customer_id, @customer.id )

Because in my Customer model name and surname are mandatory fields. 因为在我的客户模型中,姓名和姓氏是必填字段。 I still have a problem. 我还是有问题 I pushed the app on Heroku and I can sign in with my Facebook account and with other users accounts, but for some other users Facebook doesn't return the email. 我在Heroku上推送了该应用程序,并且可以使用我的Facebook帐户和其他用户帐户登录,但是对于其他一些用户,Facebook不返回电子邮件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM