Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Integrating Omniauth with Devise in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 132
    Comment on it

    In this article we will going to give privilege to users to log in by their social networking profiles.

    Here we will discuss to log in by facebook.

    First we will going to install Devise gem.

    Now when we have installed and integrated Devise.

    The first thing to do is to specify omniauth  in your Gemfile

    gem 'omniauth'
    gem 'omniauth-facebook'

    Now, run bundle

    bundle install

    Now you have add another field in users table.

    rails g migration AddColumnsToUsers provider uid

    Here, you will need to register your application by facebook and get the secret_key

    1. Login to facebook
    2. visit https://developers.facebook.com/apps/
    3. now click in Add a New App button
    4. Now click on Website icon
    5. Give a name to your app
    6. Provide other details and then hit Create
    7. Now go to the Dashboard of your app
    8. Copy the App Secret and App ID

    Now add the following line in /config/initializers/devise.rb

    config.omniauth :facebook, "App ID", "App Secret", scope: 'email', info_fields: 'email,name'

    Now create a Omniauth_callback controller in your app.

    rails g controller OmniauthCallback

    and add the following code in it

    class OmniauthCallbacksController < Devise::OmniauthCallbacksController
      
      def facebook
        @user =  User.save_omni_auth_details(request.env['omniauth.auth'])
        if @user.persisted?
          sign_in_and_redirect @user, :event => :authentication 
          set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
        else
          session["devise.facebook_data"] = request.env["omniauth.auth"]
          redirect_to new_user_registration_url
        end
      end
    
    
      def after_sign_in_path_for(resource)
        super resource
      end
      
    end

    Now add the following in your views where it is required:

    <%- if devise_mapping.omniauthable? %>
      <%- resource_class.omniauth_providers.each do |provider| %>
        <%= link_to "Sign up with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider), class: "btn btn-default navbar-btn" %><br />
      <% end -%>
    <% end -%>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: