Jared Rader
Jared Rader

Reputation: 880

Saving user's Facebook data from omniauth

I have a Rails app where a user logs in with Facebook. I want to save some of their Facebook data to my database, but I can't seem to access and save the extra information I'm requesting. For example, I want to get a Facebook user's 'About Me' info, which you get permission to access from the Facebook Graph API with user_about_me and call with bio.

I get this error:

undefined method 'raw_info' for nil:NilClass

Here's the necessary code:

omniauth.rb

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'], scope: "email,publish_stream,user_about_me"
end

user.rb

class User < ActiveRecord::Base

def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name
    user.username = auth.info.nickname
    user.image = auth.info.image
    user.email = auth.info.email
    user.bio = auth.info.extra.raw_info.bio
    user.oauth_token = auth.credentials.token
    user.oauth_expires_at = Time.at(auth.credentials.expires_at)
    user.save!
  end
end

def facebook
  @facebook ||= Koala::Facebook::API.new(oauth_token)
  block_given? ? yield(@facebook) : @facebook
rescue Koala::Facebook::APIError
  logger.info e.to_s
  nil
end
end

sessions_controller.rb

class SessionsController < ApplicationController

def create
  user = User.from_omniauth(env["omniauth.auth"])
  session[:user_id] = user.id
  redirect_to feed_path
end

def destroy
    session[:user_id] = nil
    redirect_to root_url
end
end

Why can't I get access to that info?

Upvotes: 2

Views: 1720

Answers (1)

trh
trh

Reputation: 7339

Need to take a look at the hash and see where "bio" is, but in my auth hash

 auth.info.extra.raw_info 

doesn't exist - I have

auth.extra.raw_info.bio

I'd output maybe with Rails.logger.info(auth) to give a better look at all the parts.

Upvotes: 1

Related Questions