I’ve recently been getting back into Ruby on Rails since my love-affair for CodeIgniter & PHP has wained a bit recently. I kept on building apps that required Facebook/Twitter authentication and relied heavily on the well built but rarely updated libraries like TankAuth.
If you don’t know, Rails has things called Gems, which are essentially packaged up libraries of code, usable throughout your applications within the MVC framework. Two of these, OmniAuth and Mini FB, offer a fantastically easy roll-out of a basic Facebook Connect powered app.
OmniAuth, officially, is “a flexible authentication system utilizing Rack middleware”, but it is basically a Gem you can install which handles the authentication process for services like Twitter and Facebook, leaving you to take the reigns at the callback stage. This is mind blowing for me, as a lot of the work in building apps with these services is hooking up to them, swapping tokens etc…
To get OmniAuth working with Facebook on your app is really simple. First of all, add:
to your Gemfile and run bundle install. This will add the Gem for you to start working with. Secondly, you need to create a flle in your config/ folder called omniauth.rb with:
…and thats it! Simply run the rails application and point it at localhost:3000/auth/facebook and it will prompt you to authenticate with Facebook. Bingo bango! You’ll also notice that when the application is successfully authenticated, it redirects back to localhost:3000/auth/facebook/callback, which you can do whatever you require with: creating a user, starting a session etc….
What good is being connected to Facebook if you can’t easily retrieve that juicy Connect data? That’s where the Gem Mini FB comes in. It bundles up a few methods for you to make calls and receive the data back in hash format. Set up is similarly breezy. Add the following to your Gemfile:
As with OmniAuth, that’s pretty much the work done for you, now all you have to do is making some calls. If you have already authenticated using OmniAuth then you should have a user token. You can use this, for example, to get a list of all the current users friends:
Now you’ve got an object that you can loop through using an each loop and display it however you want!
It really is incredibly simple to get a basic app up and running but the great thing about these tools is just how much it opens up. Make sure you check out this amazing tutorial from Nettuts+, which goes further than I’ve gone with the examples or head straight on over to the official Github-based wiki for OmniAuth or Mini FB.