LoginSignup
33
33

More than 5 years have passed since last update.

googleからのログイン実装

Posted at

1. 必要なgemのインストール

gem 'devise'
gem 'omniauth'
gem 'omniauth-google-oauth2'
ターミナル
$ bundle install
$ rails g devise:install
$ rails g devise user

2. deviseが作成したUserモデルにOmniAuthに必要なカラムを追加

ターミナル
$ rails g migration add_omniauth_to_users
db/migrate/add_omniauth_to_users.rb
class AddOmniauthToUsers < ActiveRecord::Migration
  def change
    add_column :users, :provider, :string
    add_column :users, :uid, :string
    add_column :users, :name, :string
    add_column :users, :token, :string
  end
end
ターミナル
$ rake db:migrate

3. deviseでOmniAuthを有効にする

deviseメソッドに:omniauthableを追加

app/models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, and :timeoutable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable
end

4. 任意のページにログインするためのリンクを貼る

application.html/erb
<%= link_to 'Signin with Google', user_omniauth_authorize_path(:google_oauth2) %>

5. ClientIDの取得

GoogleにてクライアントIDを取得する
https://console.developers.google.com/project

上記URLより
①プロジェクトを作成
②『Contacts API』『Google+ API』の2つをONにする
③認証情報を追加する
④認証済みのjavascript生成元に以下を入力(本番環境は別)
https://localhost:3000
⑤認証済みのリダイレクトURLに以下を入力(本番環境は別)
http://localhost:3000/users/auth/google_oauth2/callback
⑥『Client ID』と『Client Secret』をコピーする
⑦config/secrets.ymlに貼り付ける

config/secrets.yml
development:
  secret_key_base: XXXXXXXXXXXXXXXXX
  google_client_id: 取得した Client ID
  google_client_secret: 取得した Client Secret

⑧config/initializers/devise.rbを編集する

config/initializers/devise.rb
config.omniauth :google_oauth2,
                  Rails.application.secrets.google_client_id,
                  Rails.application.secrets.google_client_secret

6. Rails側の実装

ルーティングを定義

config/routes.rb
devise_for :users, controllers: {
    omniauth_callbacks: "users/omniauth_callbacks"
}

コールバックで呼び出されるコントローラーを定義

app/controllers/users ディレクトリを作成し、その中に omniauth_callbacks_controller.rb というコントローラーを作成

app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    @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

Userモデルのfind_for_google_oauth2メソッドを定義

app/models/user.rb
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])
    end
    user
  end

参照

33
33
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
33
33