DEV Community

Norman R.
Norman R.

Posted on

Google login using OmniAuth in Rails

After receiving numerous requests (O.k. not really “numerous” more like 1) I decided to show how to set up Omni Auth to use Google logins with your rails app. There’s a ton of info floating around on how to do it but like a lot of things in tech the methods change and become outdated. I recently used it on a test project so I figured it can be of use to someone. It’s not overly complicated but there are many steps you need to follow to make it work properly. Ready? Cool. lets get it crackin’.
To start, head over to (https://console.developers.google.com/) and click “OAuth consent screen” . Select “create project” and at the next menu add a “project name”. Click “create” to confirm then scroll down to Application home page and enter your web apps URL. For today we will be using a local host so for example you can enter https://localhost:3000. Navigate to the “User type” form and select “external”. Next scroll to “Developer Contact information” and enter your email. Select “SAVE AND CONTINUE”. Navigate to the “Credentials” tab on the left and select “OAuth client ID”. Under “Application type” form, select “web application”. 2 new selection should appear at the bottom of the page. Select “URIs* under the “Authorized redirect URIs” In the form enter http://localhost:3000/auth/google_oauth2/callback. Click save and continue. Once you finish creating the app your client id and secret should be listed.
Go back into your code editor and now we need to add 4 gems in your gemfile then run “bundle” in the terminal.

gem 'omniauth'
gem 'omniauth-rails_csrf_protection'
gem 'omniauth-google-oauth2'
gem 'bcrypt'
Enter fullscreen mode Exit fullscreen mode

Create or select the file.
config\initializers\omniauth.rb and enter the following info.

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
end
OmniAuth.config.allowed_request_methods = %i[get]
Enter fullscreen mode Exit fullscreen mode

Remember when editing middleware its best to close and reload your puma server when you make changes.
In your config\routes.rb we will add a get route for oauth to use. Enter

get '/auth/google_oauth2/callback', to: 'sessions#google_auth'
Enter fullscreen mode Exit fullscreen mode

Next you need to create an env file for your google client ID and secret. In the root folder of your app make a new file called .env enter the code then paste your secret and key.

GOOGLE_CLIENT_ID = <id here>
GOOGLE_CLIENT_SECRET = <key here>
Enter fullscreen mode Exit fullscreen mode

Make sure to add your secret and key to your gitignore file or the key will be exposed when the repo is pushed.
Now head over to or create app\controllers\sessions_controller.rb and add the following inside it.

class SessionsController < ApplicationController

  def google_auth
    @user = User.find_or_create_by(uid: auth['uid']) do |u|
      u.name = auth['info']['name']
      u.email = auth['info']['email']
      u.image = auth['info']['image']
      access_token = auth
      u.google_token = auth.credentials.token
      refresh_token = auth.credentials.refresh_token
      u.google_refresh_token = refresh_token if refresh_token.present?
      u.password = SecureRandom.urlsafe_base64
    end
    log_in @user
    redirect_to menu_path
  end

private

  def auth
    request.env['omniauth.auth']
  end

end
Enter fullscreen mode Exit fullscreen mode

The last line after the first “end” command you can change based on how your routes are set up in your app. O.K. now head to app\controllers\application_controller.rb and enter the following code

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end
Enter fullscreen mode Exit fullscreen mode

Navigate to app\helpers\sessions_helper.rb and enter the following.

module SessionsHelper

  def log_in(user)
    session[:user_id] = user.id
  end

  def current_user
    current_user ||= User.find_by(id: session[:user_id])
  end

  def logged_in?
    !current_user.nil?
  end

  def log_out
    session.delete(:user_id)
    current_user = nil
  end
end
Enter fullscreen mode Exit fullscreen mode

In your views you can add this code for a login button.

    <%= button_to "Sign in with Google", '/auth/google_oauth2', 
                    method: :get %>
Enter fullscreen mode Exit fullscreen mode

Make the file db\migrate\001_create_users.rb then enter the following.

class CreateUsers < ActiveRecord::Migration[6.1]
  def change
    create_table :users do |t|
      t.string :name
      t.string :uid
      t.string :email
      t.string :google_token
      t.string :google_refresh_token
      t.string :image
      t.string :password_digest

      t.timestamps
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

In the terminal run

rake db:migrate
Enter fullscreen mode Exit fullscreen mode

and that’s it. As of the date of this blog I can confirm this works so get it while it’s fresh! Any questions or suggestions feel free to hit me up.

Top comments (0)