LoginSignup
49
52

More than 3 years have passed since last update.

railsでomniauth-facebookを使ってFacebookログインを実装する方法

Last updated at Posted at 2018-03-01

やりたいこと

ruby on railsでFacebookログインを実装したい。

実際に検索してみると多くの記事が出てくるがFBの仕様が変更していたりしていてそのまま使える記事がないように思えるので、今回その辺りも踏まえ、手順通りにやれば誰でも簡単にできるようにまとめてみる。

Facebook側の設定

前提:先にFacebook for developersの登録を完了させておいてください。

その後このURLからウェブサイトを選択。
スクリーンショット 2018-03-01 12.52.58.png

次に表示名は適当で良いのでウェブサイトのクイックスタートを実行。ウェブサイトURLにサイトのURLを入力し次へを選択。

スクリーンショット 2018-03-01 12.54.04.png

Finished!を確認したらSkip to Developer Dashboard を選択してください。

スクリーンショット 2018-03-01 12.55.17.png

ダッシュボードにいったら後々必要になる手順をやってしまいます。

スクリーンショット 2018-03-01 12.56.34.png

設定のベーシックをクリックし、プライバシーポリシーのURLを入れてください(適当なURLでも大丈夫です)

次にアプリレビューをクリックし、「〇〇(アプリ名)を公開しますか?」とあるので公開します。(これによって開発者モードから切り替わります)

次に設定のベーシックから「アプリドメイン」を追加します。

最後にプロダクトをクリックし、Facebookログインを追加します。その後5手順くらいなんだか説明が出てきますが無視して、プロダクトの設定から有効なOAuthリダイレクトURLを追加してください。(ルートディレクトリは必須で入力が必要です)

※Facebookの仕様変更によって追加したURLの後ろに/users/auth/facebook/callbackをつける必要があるみたいです。

スクリーンショット 2018-03-01 13.01.49.png

コーディング

  1. 「devise facebook gem」などとGoogleで検索してみて欲しい。するとこのURL(OmniAuth: Overview)にたどりつく。あとは基本的にはGitHub内に書いてあるドキュメントを見ながらやっていく。

  2. gemのインストール
    下記のコードをgemfileに記載

gem 'omniauth-facebook'

3.ターミナルで以下を実行

rails g migration AddOmniauthToUsers provider:string uid:string image:string name:string
rake db:migrate

4.config/initializers/devise.rbに以下をコピペ

※APP_IDとAPP_SECRETは自分のもの(設定のベーシックから見れます)

config.omniauth :facebook, "APP_ID", "APP_SECRET", scope: 'email', info_fields: 'email,name'

5.app/models/user.rbに以下をコピペ

:omniauthable

スクリーンショット 2018-03-01 13.04.54.png

6.FBログインのリンクを適当なところに書く

<%= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path %>

7.config/routes.rbにコピペ

devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }

8.app/controllers/users/にomniauth_callbacks_controller.rbを作成し、以下をコピペ

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  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

  def failure
    redirect_to root_path
  end
end

9.app/models/user.rbに以下をコピペ

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name   # assuming the user model has a name
    user.image = auth.info.image # assuming the user model has an image
    # If you are using confirmable and the provider(s) you use validate emails, 
    # uncomment the line below to skip the confirmation emails.
    # user.skip_confirmation!
  end
end

感想

ドキュメントだけだと不十分だったり若干変更している点があって苦戦しましたがなんとかFBログインを実装することができました。

修正

・有効なOauthリダイレクトURLのところの記述を修正
※Facebookの仕様変更によって追加したURLの後ろに/users/auth/facebook/callbackをつける必要があるみたいです。

49
52
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
49
52