Friday, October 19, 2012

Devise , omniauth and rails application

Alright this is for all folks out there who think devise and omniauth will make your life easy to make you app login to fb , nope its not easy and required a lot of google search and experimentation here and there to make things happen .

So the requirement was such to allow to facebook login from the app , I chose omniauth facebook plugin for same .

Gems you need to define in your app are --



please notice the git links given beside the gems , believe me the default gems do not work for you . I had to google , regoogle try and find out stuff and finally !!! this is the correct  combination of gems which you need for your tasks

Ok execute --

 bundle install

And configure devise as provided in devise documentation

https://github.com/plataformatec/devise

Create omniauth.rb in configuration/initializers directory

place following code in the file



We will need to create one more model name Authentications to store authentication details of a user , in case he arrives from facebook

 rails g model Authentications user_id:integer provider:string uid:string token:string

Maintain one to many relationship between authentications and user so here goes code accordingly

in authentications.rb

belongs_to user

in users.rb

 has_many :authentications, :dependent => :delete_all

We need to add one callback controller function for omniauth to call . For the same purpose we will make one controller Authentications in our application

 rails g controller Authentications

Create a method name "create" with in controller called while callback


I am maintaining a session variable over here to distinguish a fb session than a normal login session , you can follow some other approach of urs if you want

create apply_omniauth in user.rb



Configure route for Authentications Controller in routes.rb

match '/auth/facebook/callback' =>  'authentications#create'

Finally place a link in your application.html.erb


<%= link_to "Sign in with Facebook", '/auth/facebook/'>


Alright so from here on you can successfully let people sign in with there fb accounts to your application

No comments:

Post a Comment