Help us understand the problem. What is going on with this article?

googleからのログイン実装

More than 3 years have passed since last update.

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

参照

http://www.ohmyenter.com/?p=668

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした