Subscribed unsubscribe Subscribe Subscribe

Rails4でソーシャルログイン(omniauth-facebook)

以下でdevise,テーブルの作成、モデルの設定が完了している前提です。

keiwt.hatenablog.com

参考にするサイト

https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

github.com

開発者登録

https://developers.facebook.com/apps

gem追加

gem 'omniauth-facebook'
$ bundle install --path=vendor/bundle

keyとsecretの設定

※以下のrails_configを使用していることが前提です

github.com

  • config/settings.yml
api:
  twitter:
    key   : XXXXXXXXXXXXXXXXXXXXXXXXXXX
    secret: XXXXXXXXXXXXXXXXXXXXXXXXXXX
  facebook:
    key   : XXXXXXXXXXXXXXXXXXXXXXXXXXX
    secret: XXXXXXXXXXXXXXXXXXXXXXXXXXX
  • config/initializers/devise.rb
Devise.setup do |config|
  config.omniauth :twitter,  Settings[:api][:twitter][:key],  Settings[:api][:twitter][:secret]
  config.omniauth :facebook, Settings[:api][:facebook][:key], Settings[:api][:facebook][:secret]
.....
end

Userモデルへの設定

  • app/models/user.rb
class User < ActiveRecord::Base
  devise :omniauthable, :omniauth_providers => [:twitter, :facebook]
  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.twitter_data"] && session["devise.twitter_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      elsif data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

※from_omniauthメソッドはある前提です

再起動

$ bundle exec rails s -b 0.0.0.0 Puma

Site URLの設定

Add Platform→Web Site→http://localhost:3000/

※Site URLを設定しないと以下のエラーになります Given URL is not allowed by the Application configuration:
One or more of the given URLs is not allowed by the App's settings.
It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

コールバック時の設定

  • app/controllers/users/omniauth_callbacks_controller.rb
def facebook
  # 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?
    sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
    # set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
  else
    session["devise.facebook_data"] = request.env["omniauth.auth"]
    redirect_to new_user_registration_url
  end
end

取得できるデータ一覧

provider
uid

info.email
info.name
info.first_name
info.last_name
info.image
info.urls.Facebook
info.verified

credentials.token
credentials.expires_at
credentials.expires

extra.raw_info.id
extra.raw_info.birthday
extra.raw_info.email
extra.raw_info.first_name
extra.raw_info.gender
extra.raw_info.last_name
extra.raw_info.link
extra.raw_info.locale
extra.raw_info.name
extra.raw_info.timezone
extra.raw_info.updated_time
extra.raw_info.verified