Thursday, 3 July 2014

Google Plus Integration

Google Plus Integration:

Step1: you need to create an app in google to get “Client Id” and “Client Secret Id”
https://code.google.com/apis/console/

  1. Clck on Project Menu
  2. Fill project name and Project Id
  3. Enable an API (I.E, GOOGLE + API), Turn off remaining all API's
  4. click on Credentails column.
  5. Click on New Client Id.(select web application,set redirect url )(EX: Redirect url:http://localhost:3000/users/auth/google_oauth2/callback)
  6. Then you will get Clent Id and Client Secret Id

Step 2: Add the gems in your gem file
gem 'devise'
gem 'omniauth'

gem 'omniauth-google-oauth2' 
then, Run bundle.

Step3:You need two more columns to store provider type and userid given from google
rails g migration AddProviderToUsers provider:string uid:string
Runt rake db:migrate to insert the columns in users table.
Step4:Go the user model “user.rb” and add the following line
devise :omniauthable, :database_authenticatable, :registerable,

         :recoverable, :rememberable, :trackable, :validatable

Step 5:Now you need to declare the provider name and client id and key.Go to the file config/initializers/devise.rb and the following line
require 'omniauth-google-oauth2'

config.omniauth :google_oauth2, "[ClentId]", "[Client Secret Id]", { access_type: "offline", approval_prompt: "" }

Step 6: Add below 2 line to your layout
<%= link_to "Sign out", destroy_user_session_path,:method => :delete %>

<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>

Step 7:Before creating the call back method change your route like below
 devise_for :users, path_names: {sign_in: "login", sign_out: "logout"},

                   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 all
    user = User.from_omniauth(request.env["omniauth.auth"])
    if user.persisted?
      flash.notice = "Signed in!"
      sign_in_and_redirect user
    else
      session["devise.user_attributes"] = user.attributes
      redirect_to new_user_registration_url
    end
  end
  alias_method :google_oauth2, :all

end
Step 9:Add the following block in your user model.
def self.from_omniauth(auth)
  where(auth.slice(:provider, :uid)).first_or_create do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.username = auth.info.nickname
    user.email = auth.info.email
  end
end
def password_required?
  super && provider.blank?
end
def update_with_password(params, *options)
  if encrypted_password.blank?
    update_attributes(params, *options)
  else
    super
  end

end

Happy Rails Coding...............

Sorce from:https://github.com/zquestz/omniauth-google-oauth2/issues/20

No comments:

Post a Comment