Skip to content

Instantly share code, notes, and snippets.

@jhsu802701
Last active January 15, 2021 18:01
Show Gist options
  • Save jhsu802701/59852684dc542a47530b0b10d3cffac6 to your computer and use it in GitHub Desktop.
Save jhsu802701/59852684dc542a47530b0b10d3cffac6 to your computer and use it in GitHub Desktop.

Cheat Sheet for Adding Google Authentication to A Ruby on Rails App

Prerequisites

A Ruby on Rails app with authentication provided through the devise gem

Elements

Google API setup

  • Go to https://console.developers.google.com and create your project.
  • In your new project, enable the Google+ API and Contacts API.
  • Go to Credentials, then select the "OAuth consent screen" tab on top, and provide your email address and product name.
  • When directed to do so, create your credentials. Select Oauth client ID. Select "web application" as the application type, "http://localhost:3000" as the authorized Javascript origin, and "http://localhost:3000/oath2callback" as the authorized redirect URI.
  • Get the client ID and client secret codes. You will need them to configure your source code.

Gemfile

  • Add the following lines to the Gemfile:
gem 'omniauth'
gem 'omniauth-google-oauth2'
  • In the command line shell, use the "bundle install" command to install these gems.

app/models/user.rb

  • Add the following line to app/models/user.rb:
devise :omniauthable, :omniauth_providers => [:google_oauth2]
  • Add the following lines to app/models/user.rb:
  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

Adding the provider and uid parameters to users

  • Enter the following commands:
rails g migration AddProviderToUsers provider:string uid:string
bundle exec rake db:migrate

config/routes.rb

Add the text "omniauth_callbacks: 'users/omniauth_callbacks'" to the "devise_for :users, controllers: {}" section. The end result should look something like:

  devise_for :users, controllers: { sessions: 'users/sessions',
    passwords: 'users/passwords', registrations: 'users/registrations',
    confirmations: 'users/confirmations',
    omniauth_callbacks: 'users/omniauth_callbacks' }

config/initializers/omniauth.rb

Add the following lines:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
end

config/initializers/devise.rb

Add the following lines to config/initializers/devise.rb:

require 'omniauth-google-oauth2'
config.omniauth :google_oauth2, 'APP_ID', 'APP_SECRET', { access_type: 'offline', approval_prompt: '' }

app/controllers/users/omniauth_callbacks_controller.rb

Add the following lines within the pre-existing class:

  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

app/views/users/sessions/new.html.erb

Add the following line:

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

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment