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
- Login to facebook
- visit https://developers.facebook.com/apps/
- now click in Add a New App button
- Now click on Website icon
- Give a name to your app
- Provide other details and then hit Create
- Now go to the Dashboard of your app
- 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)