Skip to main content

Twitter and Linkedin Integration Using Devise and Omniauth In Rails App.

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-twitter'

Run the “bundle install” command to install the gem.

Step:2
You need two more columns to store provider type and userid given from twitter

rails g migration AddProviderToUsers provider:string uid:string

Runt rake db:migrate to insert the columns in users table.

Step:3
Go the user model “user.rb” and add the following line

devise : omniauthable

Step:4
First of all you need to create an app in twitter to get “Consumer key” and “Consumer Secret key”

https://dev.twitter.com/apps

Create an app and get the App id and secret key.

Step:5
Now you need to declare the provider name and app id and key.Go to the file config/initializers/devise.rb and the following line

require 'omniauth-twitter'
config.omniauth :twitter, "APP_ID", "APP_SECRET"

Step:6
Go to your layout file and the following block


<% if user_signed_in? %>
Signed in as <%= current_user.name %>. Not you?
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or
<%= link_to "Sign in", new_user_session_path %>
<%= link_to "Sign in with Twitter", user_omniauth_authorize_path(:twitter) %>
<% end %>

When the user clicks on Sign in with Twitter link, they will redirects to the Twitter login page, after entering their credentials it will again redirect the user back to the applications Callback method .

Step:7
Before creating the call back method change your route like below


devise_for :users, :controllers => { : omniauth_callbacks => "omniauth_callbacks" }

Step:8
Create a new controller named as “omniauth_callbacks_controller.rb”.Add the following method in it.


class OmniauthCallbacksController < Devise::OmniauthCallbacksController  
def twitter
    auth = env["omniauth.auth"]

    @user = User.find_for_twitter_oauth(request.env["omniauth.auth"],current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.twitter_uid"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

Step:9
Add the following block in your user model.


def self.find_for_twitter_oauth(auth, signed_in_resource=nil)
    user = User.where(:provider => auth.provider, :uid => auth.uid).first
    if user
      return user
    else
      registered_user = User.where(:email => auth.uid + "@twitter.com").first
      if registered_user
        return registered_user
      else

        user = User.create(name:auth.extra.raw_info.name,
                            provider:auth.provider,
                            uid:auth.uid,
                            email:auth.uid+"@twitter.com",
                            password:Devise.friendly_token[0,20],
                          )
      end

    end
  end

Now we are done with twitter integration with devise.

Linkedin Integration

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-linkedin'

Run the “bundle install” command to install the gem.

Step:2
You need two more columns to store provider type and userid given from linkedin

rails g migration AddProviderToUsers provider:string uid:string

Runt rake db:migrate to insert the columns in users table.

Step:3
Go the user model “user.rb” and add the following line

devise : omniauthable

Step:4
First of all you need to create an app in linkedin to get “App Id” and “App Secret key”

http://developer.linkedin.com

Create an app and get the App id and secret key.

Step:5
Now you need to declare the provider name and app id and key.Go to the file config/initializers/devise.rb and the following line

require 'omniauth-linkedin'
config.omniauth :linkedin, "APP_ID", "APP_SECRET"

Step:6
Go to your layout file and the following block


<% if user_signed_in? %>
Signed in as <%= current_user.name %>. Not you?
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> or
<%= link_to "Sign in", new_user_session_path %>
<%= link_to "Sign in with Linkedin",user_omniauth_authorize_path(:linkedin) %>
<% end %>

When the user clicks on Sign in with Linkedin link, they will redirects to the Linked login page, after entering their credentials it will again redirect the user back to the applications Callback method .

Step:7
Before creating the call back method change your route like below


devise_for :users, :controllers => { : omniauth_callbacks => "omniauth_callbacks" }

Step:8
Create a new controller named as “omniauth_callbacks_controller.rb”.Add the following method in it.


class OmniauthCallbacksController < Devise::OmniauthCallbacksController  
def linkedin
    auth = env["omniauth.auth"]
    @user = User.connect_to_linkedin(request.env["omniauth.auth"],current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.twitter_uid"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

Step:9
Add the following block in your user model.


def self.connect_to_linkedin(auth, signed_in_resource=nil)
    user = User.where(:provider => auth.provider, :uid => auth.uid).first
    if user
      return user
    else
      registered_user = User.where(:email => auth.info.email).first
      if registered_user
        return registered_user
      else

        user = User.create(name:auth.info.first_name,
                            provider:auth.provider,
                            uid:auth.uid,
                            email:auth.info.email,
                            password:Devise.friendly_token[0,20],
                          )
      end

    end
  end  

Comments

Popular posts from this blog

Get the Current url in ruby on rails

request.refererrequest.fullpathrequest.fullpath.split("?")[0]request.referer or request.env['HTTP_REFERER'] your controller to get the referer url. 

--------------------
request.original_url
request.url
request.host_with_port
<link rel="canonical" href="<%= request.url %>" />
<%=request.path%>
How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.
request.env['REQUEST_URI']

 For Rails 3.2 or Rails 4 you should use request.original_url to get the current URL. More detail.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ?

The way to add radio buttons to your active scaffold create/update from is as shown below

#Controller

class UsersController < ApplicationController
active_scaffold :user do |config|
config.label = “Users”
config.columns = [:name, :gender]
config.columns[:gender].form_ui = :radio
config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']]
end
end