[RUBY] July 2020 google login authentication with gem Omniauth

Overview

Devise + omniauth + omniauth-google-oauth2 Implement google login with There were various articles, but I will keep it as a memorandum so that I will not forget it for the time being

Caution

1. First, register on the Google Developers Console

1-1. Preparation

See here First of all Please issue the client ID and client secret.

I tried using the Google Maps API

1.2 Added Gemfile

Once the client ID and client secret are issued Add to Gemfile

Gemfile


#abridgement
gem 'devise'
gem 'omniauth'
gem 'omniauth-google-oauth2'
...

terminal


$ bundle install

Devise settings

terminal


$ rails g devise:install

Create table for user authentication

termina


$ rails g devise user

2020******_add_column_to_users.rb


class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
    add_column  :users,  :provider,  :string
    add_column  :users,  :uid,       :string
    add_column  :users,  :token,       :string
    add_column  :users,  :meta,       :string
  end
end

$ rake db:migrate

Model modification

app/models/user.rb


class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :validatable, :confirmable,
          :omniauthable, omniauth_providers: %i(google)
...
...
...

  def self.find_for_google_oauth2(auth)
    user = User.where(email: auth.info.email).first

    unless user
      user = User.create(name:     auth.info.name,
                         provider: auth.provider,
                         uid:      auth.uid,
                         email:    auth.info.email,
                         token:    auth.credentials.token,
                         password: Devise.friendly_token[0, 20],
                         meta:     auth.to_yaml)
    end
    user
  end

end

All you need is: trackable and: omniauthable. If you want devise to have new functions, I think it's smarter to add new ones at that time. This time, the purpose is to log in for the time being, so this is fine!

Also, def self.find_for_google (auth) is a method that determines if the user is already known in the application when the callback is received. I will use it later.

config modification

It wasn't like I was on another site! !! !!

config/initializers/devise.rb


Devise.setup do |config|
    require 'devise/orm/active_record'
    config.omniauth :google_oauth2,
                    GOOGLE_CLIENT_ID="***sdps.apps.googleusercontent.com",
                    GOOGLE_CLIENT_SECRET="***********",
                    name: :google,
                    scope: %w(email) 
  end

The place of GOOGLE_CLIENT_ID is ENV = ['...'] There are many places where it is. .. It's Simple!! Regarding scope, if it is the default (state not described here), it will be email and profile. It's not required for user authentication, so let's just email

Create a page to set up a login button

ruby:app/controllers/views/home.html.erb


= link_to image_tag('#.png'), omniauth_authorize_path(resource_name, provider)

Create omniauth_callbacks_controller.rb

Create an app / controllers / users directory and create a controller called omniauth_callbacks_controller.rb.

omniauth_callbacks_controller.rb


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google
    @user = User.find_for_google_oauth2(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

Server startup

terminal


$ rails s

Then start the server and When I access http: // localhost: 3000 and press google login ...

Since routes.rb does not describe the destination to transition to after login, you are going to root. After logging in, if you try to display current_user.email etc. with view etc., you will see the email address of the logged-in user. !!

Recommended Posts

July 2020 google login authentication with gem Omniauth
[Rails] Google, Twitter, Facebook authentication using Devise and Omniauth