0

我使用设备和omniauth 在我的应用程序上创建了注册/登录功能。用户可以通过注册表单进行注册,然后登录。他们也可以通过 Facebook 登录。

但是,当我使用自己的电子邮件地址 john@whosjohn.com 注册,然后使用我的 Facebook 帐户(也使用 john@whosjohn.com)登录时,我创建了 2 个不同的用户。

我已经检查了 User.all 发生了什么,当我通过 Facebook 登录时,我没有保存电子邮件地址。值为空。

有人可以解释我如何将链接到他的 Facebook 帐户的用户电子邮件地址保存到我的用户表中吗?

用户.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable,:omniauthable, :omniauth_providers => [:facebook]

  def password_required?
    false
  end

  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
    end
  end

end
4

1 回答 1

1

尝试这个:

创建授权模型

rails g model Authorization

在迁移中添加以下代码

class CreateAuthorizations < ActiveRecord::Migration
  def change
    create_table :authorizations do |t|
      t.string :provider
      t.string :uid
      t.integer :user_id
      t.string :token
      t.string :secret
      t.timestamps
    end
  end
end

然后

rake db:migrate

在你的模型/authorization.rb

belongs_to :user

在你的模型/user.rb

has_many :authorizations

def self.from_omniauth(auth)
  authorization = Authorization.where(:provider => auth.provider, :uid => auth.uid.to_s).first_or_initialize
  authorization.token = auth.credentials.token
  if authorization.user.blank?
    user = User.where('email = ?', auth["info"]["email"]).first
    if user.blank?
     user = User.new
     user.password = Devise.friendly_token[0,10]
     user.email = auth.info.email
     user.save
    end
   authorization.user_id = user.id       
  end
  authorization.save
  authorization.user
end

希望这会帮助你。

于 2015-08-01T09:21:49.157 回答