Step-by-Step Guide: Google OmniAuth Setup

Step 1: Install the OmniAuth Gem

First, you'll need to add the OmniAuth gem and the Google OAuth2 gem to your Gemfile. Add the following lines:

gem 'omniauth-google-oauth2'
      

After updating your Gemfile, run:

bundle install
      

Step 2: Set Up Google OAuth Credentials

Next, go to the Google Cloud Console and create a new project. Then navigate to APIs & Services and create OAuth 2.0 credentials.

Step 3: Set Up Environment Variables

To protect your Google OAuth credentials, store them in environment variables using a .env file.

# .env
GOOGLE_OAUTH_CLIENT_ID="your-client-id"
GOOGLE_OAUTH_CLIENT_SECRET="your-client-secret"
      

Replace your-client-id and your-client-secret with the values you copied from Google Cloud Console.

Step 4: Configure OmniAuth in Rails

Create or update the file config/initializers/omniauth.rb with the following code to configure OmniAuth to use your Google OAuth credentials:

# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_OAUTH_CLIENT_ID'], ENV['GOOGLE_OAUTH_CLIENT_SECRET'], {
    scope: 'email,profile',
    prompt: 'select_account',
  }
end
      

Step 5: Create Routes for OmniAuth

Next, update your config/routes.rb file to add routes for OmniAuth callbacks:

# config/routes.rb
Rails.application.routes.draw do
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  delete 'logout', to: 'sessions#destroy'
end
      

Step 6: Create the Sessions Controller

Now, create a SessionsController to handle the callback from Google OAuth:

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def create
    user_info = request.env['omniauth.auth']
    user = User.find_or_create_by(email: user_info['info']['email']) do |u|
      u.name = user_info['info']['name']
      u.image = user_info['info']['image']
    end
    session[:user_id] = user.id
    redirect_to root_path, notice: 'Signed in successfully'
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path, notice: 'Signed out successfully'
  end
end
      

Step 7: Add Login and Logout Links

Finally, add login and logout links to your application views. You can use the following example for a basic implementation:

# app/views/layouts/application.html.erb
<% if session[:user_id] %>
  Logged in as <%= User.find(session[:user_id]).name %> |
  <%= link_to 'Logout', logout_path, method: :delete %>
<% else %>
  <%= link_to 'Login with Google', '/auth/google_oauth2' %>
<% end %>
      

Conclusion

You have now successfully set up Google OmniAuth in your Rails application. You can log in and log out using Google credentials, and the user's data will be stored in your application session.

Remember to never commit your .env file to version control. Instead, use services like Heroku or Docker to manage environment variables in production.