Search code examples
rubyruby-on-rails-3oauthomniauth-facebook

Getting information from Facebook OmniAuth Authentication Hash


I am a beginner with Ruby and Rails but I managed to use OmniAuth for authentication via Facebook. Everything works fine, I am able to create users and they are able to login with Facebook.

The problem is, I would like to take some of the user data (such as email, profile photo, etc.) and save it.

Going through the README (https://github.com/mkdynamic/omniauth-facebook), I managed to find:

Here's an example Authentication Hash available in request.env['omniauth.auth']:

{
  :provider => 'facebook',
  :uid => '1234567',
  :info => {
    :nickname => 'jbloggs',
    :email => '[email protected]',
    :name => 'Joe Bloggs',
    :first_name => 'Joe',
    :last_name => 'Bloggs',
    :image => 'http://graph.facebook.com/1234567/picture?type=square',
    :urls => { :Facebook => 'http://www.facebook.com/jbloggs' },
    :location => 'Palo Alto, California',
    :verified => true
  }
} 

I tried to do more searching on the Authentication Hash and got this which lists some of the information that can be fetched: https://github.com/intridea/omniauth/wiki/Auth-Hash-Schema

The thing is, I asked for certain permissions. The question is, how do I know what sort of information Facebook is sending? Unfortunately, saying the info is in request.env['omniauth.auth'] does me not much good. How do I fetch the information from here?

I am a real beginner going through the Rails tutorial (http://ruby.railstutorial.org/) but trying to create my own app by trial and error.


Solution

  • request.env['omniauth.auth'] will give you a hash. Check the Ruby docs for what you can do with a hash.

    http://ruby-doc.org/core-1.9.3/Hash.html

    For any elements that are not always going to be there you can just check for blank? (a Rails convenience method), e.g.

    omniauth = request.env['omniauth.auth']
    unless omniauth['info']['email'].blank?
      send_spam omniauth['info']['email'] # ;)
    end
    

    You would probably find the following screencast useful if you haven't seen it already:

    http://railscasts.com/episodes/235-omniauth-part-1