Skip to main content

Google Integration Using Devise and Omniauth In Rails App.

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-google-oauth2'

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

Step:2
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.

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 google to get “Client key” and “Client Secret key”

https://code.google.com/apis/console/

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

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, "APP_ID", "APP_SECRET", { access_type: "offline", approval_prompt: "" }

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 Google", user_omniauth_authorize_path(:google_oauth2) %>
<% end %>

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 google_oauth2
    
    @user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.google_data"] = 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_google_oauth2(access_token, signed_in_resource=nil)
    data = access_token.info
    user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first
    if user
      return user
    else
      registered_user = User.where(:email => access_token.info.email).first
      if registered_user
        return registered_user
      else
        user = User.create(name: data["name"],
          provider:access_token.provider,
          email: data["email"],
          uid: access_token.uid ,
          password: Devise.friendly_token[0,20],
        )
      end
   end
end

Comments

Popular posts from this blog

Error malloc(): memory corruption nginx with passenger?

Error malloc(): memory corruption nginx with passenger Passenger issue resolving steps :  sudo gem uninstall passenger(uninstall all passenger) sudo gem install passenger sudo passenger-install-nginx-module --auto --auto-download --prefix=/opt/nginx --extra-configure-flags=none Update nginx config file with new passenger version and restart the nginx

PayUMoney Integration in Ruby on Rails

PayUMoney Integration in Ruby on Rails Generating Cheksum in Payu    Hash or Checksum = sha512(key|txnid|amount|productinfo|firstname|email|u df1|udf2|udf3|udf4|udf5||||||salt) Controller Code Will be def payumoney   @key = "gtKFFx"   @salt =  "eCwWELxi"   val = "#{key|txnid|amount|productinfo|firstname|email|u df1|udf2|udf3|udf4|udf5||||||#{@salt}"  @checksum = Digest::SHA512.hexdigest("#{val}") end <form action="https://test.payu.in/_payment" method='post' id='sub'  >     <input type="hidden" name="key" value="<%=@key%>">     <input type="hidden" name="hash" value="<%=@checksum%>">     <input type="hidden" name="txnid" value="TXN1234">     <input type="hidden" name="amount" value="200">     <input type="hidden" name=...

RSPEC TESTCASES FOR MODEL VALIDATIONS IN RAILS

describe User do    before(:each) do     @user_new = { :name => "chinna",:email => "chinna@yopmail.com",:password => "chinnaram",:password_confirmation => "chinnaram"}    end it "should create a new user details" do      @user_attr = User.create!(@user_new) end ##validations in your model ########### User.rb(your model your mention like that....) validates :name,:email,:presence => true validates :name,:uniqueness => true validates_attachment_content_type :image, :content_type => ['image/jpeg', 'image/png','image/pjpeg','image/x-png','image/gif'] ###validation for name presence it "should require a name" do      user = User.new(@user_attr.merge(:name => ""))      user.should_not be_valid   end #validation for email presence  it "should require a email" do      user = User.new(@user_attr.merge(:email => ""))      user...