Facebook Connect : Working with offline user’s data access
Posted: September 9th, 2009 | Author: Pierre Olivier Martel | Filed under: Facebook, Rails | View CommentsThis the third article of a series of 4 articles on Facebook Connect. It assumes you’re using Rails and the Facebooker gem.
In my Facebook Connnect salsa network application, I have a cron task that runs each night to create new Facebook events associated with clubs. So for example, if there is a salsa night every Tuesday at Moe’s bar, the related Facebook event will be created 7 days in advance on behalf of the administrator of the bar. But in order to create the events on behalf of a Facebook user that doesn’t have an active session on the site, there is a few steps to follow.
1- Request the offline_access extended permission
Some of the Facebook API functionalities require you to get permission from the user first. In this case, we need the offline_permission to access user’s data.
<div id="grant-permissions">
<fb:prompt-permission perms="offline_access" next_fbjs="$('#grant-permissions').hide()">
Click here to grant offline access!
</fb:prompt-permission>
</div>
The previous line can be inserted in your view. The XFBL code creates a link to a popup prompt asking the user for offline access permission. The next_fbjs attribute is a javascript callback function that executes once the user has granted or refused the permission. In this case, we just hide the div using a jQuery function.
2- Store the user’s infinite session key
If the user has granted the offline_access permission, each request will now contain an infinite session key. We need to store this information somewhere in the DB if it’s not already there. In this case, I added a session_key attribute to my User model.
# This goes in your application_controller.rb
before_filter :set_fb_session_key
def set_fb_session_key
if logged_in? && facebook_session.infinite? && !current_user.fb_session_key
current_user.update_attribute(:fb_session_key, facebook_session.session_key)
end
end
You will notice that the keys have this format <random hexadecimal key>-<facebook user_id>
3- Use the session key to access user’s data
Finally, you will be able to access your user’s datas through the Facebooker API by initalizing the session with the user’s session key this way:
facebook_session = Facebooker::Session.create
facebook_session.secure_with!(user.fb_session_key)
That’s it! You can now use the user’s data as you wish!
Passionate web developer living in Montreal and hacking in Ruby on Rails available for contracts and freelance work.