# in app/models/user.rb
devise :omniauthable, omniauth_providers: [:google_oauth2]
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data['name'],
# email: data['email'],
# password: Devise.friendly_token[0,20]
# )
# end
user
end
OmniauthCallbacksControllerに追記
コントローラーにgoogle_auth2メソッドを定義します!
# in app/controllers/user/OmniauthCallbacksController.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.from_omniauth(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'].except(:extra) # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end
end
end
viewファイルに記述
Google認証に飛ばしたいviewファイルに記述します。
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>
# Deviseのバージョンが4.1.0以下の場合
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
【番外編】config/initializers/omniauth.rbに追記
deviseを使わずに認証機能を実装している方はこちらを
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, Rails.application.credentials.google[:client_id], Rails.application.credentials.google[:client_secret]
end