Save Facebook user data into the database after Authentication using Oauth2

November 13, 2011 § 3 Comments

This post is a reply from someone who emailed me, he asked me how to save the user data that already login to our site using facebook graph API.
after we create a login scheme using facebook and oauth2 gem, we need to save the facebook user data to our databases, so.. how to save it into the database?

it’s very easy and simple, when we get a callback from the facebook graph API and save the user data in session like this:

session[:fb_user] = JSON.parse access_token.get('/me')
session[:user] = User.save_user_data(session[:fb_user])

it just need to create a class method “save_user_data” in the user model with the session[:fb_user] as parameter, something like this :

def self.save_user_data(fbsession)
  user = User.new(prepare_data_from_facebook(fbsession))
  user.save(false)
end

  protected

def self.prepare_data_from_facebook(user)
  hash = {
    :guid => user["id"],
    :city =>  user["location"]["name"],
    :first_name => user["first_name"],
    :last_name => user["last_name"],
    :birth_date => user["birthday"],
    :email_address => user["email"],
    :photo => user["picture?type=large"]
  }
  return hash
end

my previous blog post was so old style, now.. we can use Devise with omniauth, it’s make your life easier and save your time.. hehe
also you can use koala gem or another gem that related with facebook hosted in github.

Advertisements

Tagged: , , , ,

§ 3 Responses to Save Facebook user data into the database after Authentication using Oauth2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Save Facebook user data into the database after Authentication using Oauth2 at Kubid on rails blog.

meta

%d bloggers like this: