I've created a sign up/in feature on my app using device and omniauth. Users can sign up through a sign up form and then sign in. They can also sign in through 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.
I've check with User.all what's going on and when I log in throughFacebook I'm not saving an email adres. 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?
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
belongs_to :user
In your models/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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.