简体   繁体   English

使用Omniauth-facebook和Devise在数据库中插入Facebook电子邮件地址

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

I've created a sign up/in feature on my app using device and omniauth. 我已经使用设备和omniauth在我的应用程序上创建了注册/登录功能。 Users can sign up through a sign up form and then sign in. They can also sign in through Facebook. 用户可以通过注册表单进行注册,然后登录。他们还可以通过Facebook登录。

But when I sign up with my own email adres john@whosjohn.com and then sign in with my Facebook account which also uses john@whosjohn.com I've created 2 different users. 但是,当我使用自己的电子邮件地址john@whosjohn.com进行注册,然后使用也使用john@whosjohn.com的Facebook帐户进行登录时,我已经创建了2个不同的用户。

I've check with User.all what's going on and when I log in throughFacebook I'm not saving an email adres. 我已经与User.all进行了联系,当我通过Facebook登录时,我没有保存电子邮件地址。 The value is nill. 该值为零。

Can someone explain how I can save the users email adres that's linked to his Facebook account into my user table? 有人可以解释如何将与他的Facebook帐户相关联的用户的电子邮件地址保存到我的用户表中吗?

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

Try this: 尝试这个:

Create a Authorization model 创建授权模型

rails g model Authorization

In migration add following code 在迁移中添加以下代码

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

then 然后

rake db:migrate

In your models/authorization.rb 在您的模型/authorization.rb中

belongs_to :user

In your models/user.rb 在您的模型/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

Hope this will help you. 希望这会帮助你。

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

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