0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】Facebookでログインできるようにする

Posted at

バージョン

Rails 5.1.6
ruby 2.4.0

前提

devise導入済み
herokuにデプロイする

1.Gemfileの編集

gem 'omniauth'
gem 'omniauth-facebook'

を追加して

$ bundle 

2. Facebook Developerの登録

https://developers.facebook.com/
にてアクセス

Screen Shot 0001-12-11 at 15.34.25.png

Screen Shot 0001-12-11 at 15.35.39.png

facebookログインを追加

すると、右側のメニューにfacebookログインという項目が追加される

3.色々な設定

Screen Shot 0001-12-11 at 15.40.06.png

プライバシポリシーのURLを埋める
私の場合、プライバシーポリシのページを作ってなかったので適当に拝借しました

本番環境では有効なOAuthリダイレクトURIの設定が必要

facebookログイン > 設定 > 有効なOauthリダイレクトURLに
...(サイトURL)/users/auth/facebook/callbackを設定

4.Railsでの設定

omniauth用のカラムをuserモデルに追加

$ rails g migration add_columns_to_users provider uid name image
$ rails db:migrate
config/initializers/devise.rb
Devise.setup do |c|
  c.omniauth :facebook, 'App ID', 'App Secret'
end

※ このままgitのリモートリポジトリにあげないこと

userモデルにメソッドを追加

models/user.rb
class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :omniauthable # :omniauthable を追加

  def self.form_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |u|
      u.provider = auth.provider
      u.uid      = auth.uid
      u.name     = auth.name
      u.email    = auth.info.email
      u.password = Devise.friendly_token[0, 20]
      u.image    = auth.info.image.gsub("picture", "picture?type=large") if u.provider == "facebook"
   end
  end
end

コールバックの設定

config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"
  devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
end

コントローラの設定

controllers/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"]
    
    if @user.persisted?
      sign_in_and_redirect @user, event: authentication
      set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"].except("extra")
      redirect_to new_user_restration_url
    end
  end

  def failure
    redirect_to root_path
  end
end
0
3
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
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?