Making OmniAuth, Devise and Koala work together
Asked Answered
R

1

6

I have an app in which I am implementing authentication using devise and omniauth. Ive got the logging in / out etc figured out, what i wanted to know was, what is the most efficient way to have a connection to the users graph api end point initialised and ready for use within my application.

eg: If on the profile page i wanted to do,

profile_image = current_user.fbgraph.get_picture("me")

How would I accomplish this with the least number of API calls (i will be using similar calls throughout the application)

Rheotaxis answered 30/6, 2011 at 9:57 Comment(0)
S
9

You can accomplish this using something like Koala. When you authenticate the user, you can grab the access token. Assuming you've followed the Devise/Omniauth tutorial, you could do something like so:

  def self.find_for_facebook_oauth(response, signed_in_resource=nil)
    data = response['extra']['user_hash']
    access_token = response['credentials']['token']
    user = User.find_by_email(data["email"])
    # only log in confirmed users
    # that way users can't spoof accounts
    if user and user.confirmed?
      user.update_attribute('fb_access_token', access_token) 
      user
    end
  end

Once you have the access token, you could then do something like:

@graph = Koala::Facebook::API.new(@user.fb_access_token)
profile_image = @graph.get_picture("me")

In my app, I check to see if a user is logged in when the callback from Facebook comes. If they are, I assume the request was to link accounts. If they're not, I assume it's a login request.

Staton answered 4/8, 2011 at 18:55 Comment(2)
Small note: with latest Koala, the line above should read @graph = Koala::Facebook::API.new(@user.fb_access_token) (GraphAPI is now just API).Nerynesbit
Where would you put the @graph = Koala::Facebook::API.new(@user.fb_access_token) line of code? (assuming we're using devise and omniauth). Also, the self.find_for_facebook_oauth code looks completely different from mine, though I followed exactly how the devise wiki showed me to do.Finegrain

© 2022 - 2024 — McMap. All rights reserved.