Step 1:
In gemfile added gem:-
gem "omniauth-google-oauth2"
Step 2:
Go to 'https://console.developers.google.com'
Step 3:
config/initializers/devise.rb:-
config.omniauth :google_oauth2, ['client_id', 'secret_key']
Step 4:
create omniauth_callbacks_controller
devise/omniauth_callbacks_controller.rb
class Devise::OmniauthCallbacksController < ApplicationController
def google_oauth2
begin
@user = User.find_for_google_oauth2(request.env['omniauth.auth'], session[:provider])
session[:user_id] = @user.id
sign_in @user
session[:provider] = nil
flash[:success] = "Welcome, #{@user.name}!"
rescue
flash[:warning] = "There was an error while trying to authenticate you..."
end
redirect_to after_sign_in_path_for(@user)
end
def failure
redirect_to root_path
end
end
Step 5:
config/routes:
devise_for :users, :controllers => {:omniauth_callbacks => "devise/omniauth_callbacks" }
get 'auth/:provider/callback', to: 'sessions#create'
get 'logout', to: 'sessions#destroy'
get 'failure' => 'devise/omniauth_callbacks#google_oauth2'
get 'google_oauth2' => 'devise/omniauth_callbacks#google_oauth2'
Step 6:
app/model/user.rb
def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
data = access_token.info
domain_info = data.email.split("@").last
if domain_info == "ascratech.com" or domain_info == "ascratech.in"
user = User.where(:email => data["email"], :provider => "google").first
unless user
devise_user = User.find_by_email(data["email"])
unless devise_user
user = User.new(:name => data["name"],
:provider => "google",
:email => data["email"],
:password => Devise.friendly_token[0,20]
)
user.skip_confirmation!
user.save
else
devise_user.provider = "google"
devise_user.name = data["name"]
devise_user.save
user = devise_user
end
end
return user
end
end
No comments:
Post a Comment