簡體   English   中英

使用Omniauth-facebook和Devise在數據庫中插入Facebook電子郵件地址

[英]Insert Facebook email address in database with Omniauth-facebook and Devise

我已經使用設備和omniauth在我的應用程序上創建了注冊/登錄功能。 用戶可以通過注冊表單進行注冊,然后登錄。他們還可以通過Facebook登錄。

但是,當我使用自己的電子郵件地址john@whosjohn.com進行注冊,然后使用也使用john@whosjohn.com的Facebook帳戶進行登錄時,我已經創建了2個不同的用戶。

我已經與User.all進行了聯系,當我通過Facebook登錄時,我沒有保存電子郵件地址。 該值為零。

有人可以解釋如何將與他的Facebook帳戶相關聯的用戶的電子郵件地址保存到我的用戶表中嗎?

user.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

嘗試這個:

創建授權模型

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

希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM