Social Login: Login with Google Account
Hello there..
In this article I would share about creating user login with devise and their Google account. I assume that you already know how to integrate devise with your rails application.
Devise installation
Add to your Gemfile
gem "devise"
then do:
$ bundle install
$ rails generate devise:install
$ rails generate devise MODEL_NAME
Replace MODEL_NAME with User if you have User as your model name, then you should create/modify your Views and Controller accordingly
OmniAuth Google OAuth2 Installation
Add to your Gemfile
gem "omniauth-google-oauth2"
then run bundle install
Define your application id and secret in config/initializers/devise.rb
config.omniauth :google_oauth2, "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", { }
get your GOOGLE_CLIENT_ID
and GOOGLE_CLIENT_SECRET
:
- Go to https://console.developers.google.com
- Create your project.
- Click ‘Enable and manage APIs’.
- Make sure “Contacts API” and “Google+ API” are on.
- Click Create credentials
- on Where will you be calling the API from? choose “web server”
- on What data will you be accessing? choose “user data”
- Type http://localhost:3000/users/auth/google_oauth2/callback in Authorized redirect URIs ( for development, change it if you’re on Production)
- Then Click Oauth Client ID
- provide an ‘EMAIL ADDRESS’ and a ‘PRODUCT NAME’
- then download Credentials
- You can find
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET
in your downloaded credential json file.
Then add the following to config/routes.rb
to define callback routes.
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
Create call back controller file app/controller/user/omniauth_callbacks_controller.rb and enter these lines
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
@user = User.from_omniauth(request.env["omniauth.auth"])
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
end
and these on your model app/models/user.rb
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(:email => data["email"]).first
unless user
password = Devise.friendly_token[0,20]
user = User.create(name: data["name"], email: data["email"],
password: password, password_confirmation: password
)
end
user
end
and finally on your views, you can login using:
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>
you can dig deeper on gem’s github repo : https://github.com/zquestz/omniauth-google-oauth2
Have a nice day…