Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook authentication data returns nil, except name and email

I used the Devise gem to set up a User model for my app. I'm trying to work in Facebook authentication using Omniauth. I can retrieve the Name and Email data, but I'm having trouble getting any other public_profile data. In this example I'm trying to get Gender, but none of the other data works either. When I visit this path: user_omniauth_authorize_path(:facebook), the "facebook" action in "controllers/registrations_controller.rb" is called. But for the user that is created, user.gender, and all other data other than name and email, comes back nil.

config/initializers/devise.rb

config.omniauth :facebook, "<ID>", "<SECRET>", scope: 'email', display: 'popup', info_fields: 'email,name,gender'

app/models/devise.rb

  devise :omniauthable, :omniauth_providers => [:facebook]
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.gender = auth.extra.raw_info.gender.to_s
    end
  end

app/controllers/registrations_controller.rb

  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

gemfile

gem 'devise'
gem 'omniauth-facebook'

What's strange is I can't even get the class type of the data. Name and Email return "String" if I call class.to_s on them, but all the other data returns "NilClass".

What am I doing wrong?

UPDATE:

Okay I literally have no idea what could have possibly changed, but this same exact code now suddenly works....so problem solved I guess?

like image 322
Joe Morano Avatar asked Sep 09 '16 03:09

Joe Morano


3 Answers

Try This way

def self.from_omniauth(access_token)
  data = access_token.info
  email      = data.info.email
  first_name = data.first_name
  last_name  = data.last_name
end
like image 199
bk chovatiya Avatar answered Nov 18 '22 07:11

bk chovatiya


You can gender attribute using auth.info.gender

where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
  user.gender = auth.info.gender
end
like image 21
Prashant4224 Avatar answered Nov 18 '22 07:11

Prashant4224


You sure the user has these data as public info?

I would try to debug the permissions in Facebook's open graph explorer https://developers.facebook.com/tools/explorer/

That will help you understand wether it is permissions, lacking data issue or a problem with the integration.

like image 1
Guy Dubrovski Avatar answered Nov 18 '22 08:11

Guy Dubrovski