Search code examples
ruby-on-railsruby-on-rails-4omniauthomniauth-facebook

Rails 4 Facebook authentication - additional information


I have used stackoverflow for over a year now, and always found an answer by searching. However, I couldn't find an answer for this problem, so this week is my first question:

I followed Ryan Bates RailsCast #360 on how to authenticate a user in Rails using the omniauth-facebook gem, and after searching around for a long time managed to adapt it for Rails 4.

Unfortunately, when I try to expand on his program by pulling the first_name and last_name that is (meant to be?) sent along with the other details in the hash, I cannot get it to work. I managed to get the email address in another program and even the image, but first_name and last_name is not being sent. I get the following returned when I raise request.env["omniauth.auth"].to_yaml in sessions#create

--- !ruby/hash:OmniAuth::AuthHash 
provider: facebook 
uid: '105531523151136' 
info: !ruby/hash:OmniAuth::AuthHash::InfoHash 
name: Donna Alajhbhfedabi Bushakwitz 
image: http://graph.facebook.com/105531523151136/picture
...

Here's my omniauth.rb initializer

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, FACEBOOK_CONFIG['app_id'], FACEBOOK_CONFIG['secret']
end

And my user.rb file:

class User < ActiveRecord::Base
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.first_name = auth.info.first_name
      user.last_name = auth.info.last_name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

Any help would be great. I have been trying to figure out what is wrong for the last 3 days.


Solution

  • Just add this line to your initializer:

    info_fields: 'first_name, last_name'