LoginSignup
27
19

More than 3 years have passed since last update.

Rails googleを使ったSNS認証

Last updated at Posted at 2020-07-31

ゴール

googole認証のリンクをクリック
image.png

アカウントを選択する
image.png

認証成功!!
image.png

ベースの作成

  • deviseを導入する
  • scaffoldで投稿機能を作成 ezgif.com-video-to-gif (1).gif

ログインして、投稿を作成できるアプリケーションを作成しました。

googleの設定をする

image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
URLは開発環境の場合、こちらを入力してください
http://localhost:3000/users/auth/google_oauth2/callback
本番環境でも使われる場合は、こちらを入力してください
http://本番環境URL/users/auth/google_oauth2/callback

コード編集していきます

環境変数の設定をします。

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']

私は環境変数の管理にdotenv-railsを使用しました。

gemfile
gem 'dotenv-rails'

bundle installします。
アプリケーションのルートディレクトリ直下に.envを作成します

以下のクライアントID,クライアントシークレットをコピーして

image.png

.envに以下のように貼り付けします

.env
GOOGLE_CLIENT_ID='クライアントIDを入力'
GOOGLE_CLIENT_SECRET='クライアント シークレット'

環境変数は、githubにpushする場合は.env.ignoreに追加しておくと良いかと思います。

.ignore
# 以下を追記
.env

gemfile編集

gemfile
gem 'omniauth-google-oauth2'

上記のgemを追加して

bundle install

ルーティング編集

gemfile
Rails.application.routes.draw do
  # deviseのコントローラを編集するときは以下を記述しないと変更が反映されないので注意
  devise_for :users, controllers: {
    # deviseの階層を編集した場合は適宜pathを編集してください
    omniauth_callbacks: "users/omniauth_callbacks"
  }

  resources :posts

  root 'posts#index'
end

データベースにカラムを追加する

認証に必要なカラムproviderカラムと、uidカラムを作成するためのマイグレーションファイルを作成します

$ rails g migration AddOuthColumnToUsers provider:string uid:string

rails db:migrate

userモデルを編集

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,
         # 以下を追加
         # google以外の認証をする場合は %i[twitter, facebook]などとなります
         :omniauthable, omniauth_providers: %i[google_oauth2]

  # クラスメソッドを作成します
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      # deviseのuserカラムに name を追加している場合は以下のコメントアウトも追記します
      # user.name = auth.info.name
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
    end
  end
end

ここで出てくるfirst_or_createが初めて使うメソッドでした。
結構便利だなと、、、

DBにwhereで検索したオブジェクトが存在しなければ、何も処理を行わず、
DBにwhereで検索したオブジェクトが存在していれば、userオブジェクトにdo以降の処理を入力してDBに保存する処理になってます。

一度rails console -sなどを使っていろいろ試してみると良いかと!
rails console -sを使えばデータベースに変更が加わらないので安心です。

omniauthの処理を編集します

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.rbで記述したメソッド(from_omniauth)をここで使っています
    # 'request.env["omniauth.auth"]'この中にgoogoleアカウントから取得したメールアドレスや、名前と言ったデータが含まれています
    @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

以上でgoogleでsns認証ができるかと思います!!

参考

Facebook/Twitter/Googleでのユーザー登録をDevise & Omniauthを使って爆速で実装する

27
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
19