I'm encountering an issue with this tutorial to write a Facebook authentification system.
First, I had an error ActiveModel::ForbiddenAttributesError. I corrected it with coderhs answer.
Now when I log in with Facebook it works, but when I log in with annother account, it overwrites the previous user in my table, so I can't have more than one Facebook user connected at the same time and still keep user information about them.
User.rb
def self.from_omniauth(auth)
where(auth.slice(provider: auth.provider, uid: auth.uid)).first_or_create.tap do |user|
user.provider ||= auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
EDIT I noticed first_or_create edit the last query inserted and do not create entry, i added it:
User.rb
def self.from_omniauth(auth)
where(auth.slice(uid: auth.uid)).first_or_create.tap do |user|
if user.uid == auth.uid
puts "\nUserModel:_________" + auth.provider + " - " + auth.uid + "\n"
else
puts "\nUnknown user " + auth.uid
end
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save
end
end
When i sign-in with a 2nd account, the else puts is displayed in the console but it edit and not create a new row in the table
Edit2 [Solution]
User.rb
def self.from_omniauth(auth)
User.find_or_create_by(uid: auth.uid).tap do |user|
if user.uid == auth.uid
puts "\nUserModel:_________" + auth.provider + " - " + auth.uid + "\n"
else
puts "\nUnknown user " + auth.uid
end
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.email = auth.info.email
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save
end
end
[Second question solved by Oleksandr Avoyants]I also want to know how to get the email from the Facebook user. I tried to add
user.email = auth.email
...but it was too easy to be true.