SNS authentication using Rails google

goal

Click the google authentication link image.png

Select an account image.png

** Authentication successful !! ** image.png

Creating a base

--Introduce devise --Create a posting function with scaffold ezgif.com-video-to-gif (1).gif

I have created an application that allows me to log in and create posts.

Set up google

image.png image.png image.png image.png image.png image.png image.png image.png image.png image.png If the URL is a development environment, please enter this http://localhost:3000/users/auth/google_oauth2/callback If you want to use it in production environment, please enter here http: // production environment URL / users / auth / google_oauth2 / callback

I will edit the code

Set environment variables.

devise.rb


# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']

I used dotenv-rails to manage environment variables.

gemfile


gem 'dotenv-rails'

bundle install. Create .env directly under the application root directory

Copy the following client ID, client secret

image.png

Paste it into .env as follows

.env


GOOGLE_CLIENT_ID='Enter client ID'
GOOGLE_CLIENT_SECRET='Client secret'

For environment variables, I think it's a good idea to add .env to .ignore when pushing to github.

.ignore


#Add the following
.env

gemfile edit

gemfile


gem 'omniauth-google-oauth2'

Add the above gem

bundle install

Routing edit

gemfile


Rails.application.routes.draw do
  #Please note that when editing the devise controller, the changes will not be reflected unless the following is described.
  devise_for :users, controllers: {
    #If you edited the devise hierarchy, edit the path accordingly.
    omniauth_callbacks: "users/omniauth_callbacks"
  }

  resources :posts

  root 'posts#index'
end

Add a column to the database

Create the column provider column required for authentication and the migration file to create the ʻuid` column

$ rails g migration AddOuthColumnToUsers provider:string uid:string

rails db:migrate

edit user model

I will write the process in ʻuser.rb`

user.rb



class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         #Add the following
         #When authenticating other than google%i[twitter, facebook]And so on
         :omniauthable, omniauth_providers: %i[google_oauth2]

  #Create a class method
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      #If you have added name to the user column of devise, add the following comment out as well.
      # user.name = auth.info.name
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
    end
  end
end

The first_or_create that appears here was the first method to use. It's quite convenient ...

If the object searched by where does not exist in the DB, nothing is done and nothing is done. If the object searched by where exists in the DB, the process after do is input to the ʻuser` object and saved in the DB.

I wondered if I should try various things using rails console -s etc. once! Rest assured that using rails console -s will not make any changes to your database.

Edit the omniauth process

omniauth_callbacks_controller.rb


# frozen_string_literal: true

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  # callback for google
  def google_oauth2
    callback_for(:google)
  end

  def callback_for(provider)
    #User earlier.Method described in rb(from_omniauth)Is used here
    # 'request.env["omniauth.auth"]'This includes the email address obtained from your googole account and data such as your name.
    @user = User.from_omniauth(request.env["omniauth.auth"])
    sign_in_and_redirect @user, event: :authentication
    set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?
  end

  def failure
    redirect_to root_path
  end
end

With the above, I think that sns authentication can be done with google! !!

reference

[Implement user registration on Facebook / Twitter / Google at explosive speed using Devise & Omniauth] (https://qiita.com/kazuooooo/items/47e7d426cbb33355590e)

Recommended Posts

SNS authentication using Rails google
[Rails] Implementation of SNS authentication (Twitter, Facebook, Google) function
[Rails] Google, Twitter, Facebook authentication using Devise and Omniauth
[Rails 6] Implementation of new registration function by SNS authentication (Facebook, Google)
Create authentication function in Rails application using devise
Implementation of Google Sign-In using Google OAuth 2.0 authentication (server edition)
Search function using [rails] ransack
Try using view_component with rails
[Rails] Save images using carrierwave
Japaneseize using i18n with Rails
[Rails] Japanese localization using rails-i18n
Implement LTI authentication in Rails
About errors during SNS authentication
[Rails] Test code using Rspec
Organize Rails routing using draw
Ajax bookmark function using Rails
Error when using rails capybara
[Rails] Try using Faraday middleware
Detailed tips when using Rails
Error when introducing SNS authentication
[Rails 6] Star-shaped review using Raty.js
Memorandum [Rails] User authentication Devise
[Implementation procedure] Create a user authentication function using sorcery in Rails
What I was addicted to when implementing google authentication with rails
Spring Boot Tutorial Using Spring Security Authentication
Get PV (views) using Impressionist ~ Rails
[Rails] Tag management function (using acts-as-taggable-on)
[Rails 6] API development using GraphQL (Query)
Password hashing and authentication using JBcrypt
[Rails 6] destroy using the resources method
[Rails] Status update using Rake task
[Rails] Reflection to db using seeds.rb
[Rails 6] Register and log in with Devise + SNS authentication (multiple links allowed)