LoginSignup
10
8

More than 5 years have passed since last update.

Rails deviseでfacebookログイン機能実装する

Posted at

gemを入れる

Gemfile
gem 'devise'
gem 'omniauth-facebook'
$ bundle install

Userモデル作成

$ rails g devise:install
$ rails g devise user

providerカラム、uidカラム作成

デフォルトで設定されているカラムのようなので、おとなしくレファレンス通りに設置。

$ rails g migration AddOmniauthToUsers provider:string uid:string
$ rake db:migrate

facebook developers登録

ここらから登録できます。
https://developers.facebook.com

登録後、アプリ名を入力し、このダッシュボードまで行きましょう。その後、”プラットフォームの追加”からウェブサイトを登録でlocalhostを登録しておきましょう。ウェブサイトに登録していないとエラーがでました。

fb01.png


deviseの設定

環境変数で登録します。

config/initializers/devise.rb
Devise.setup do |config|
  #ここを追加
  #:facebook,アプリケーションID,シークレットキーの順
  config.omniauth :facebook,ENV['PICTWEET_FB_ID'],ENV['PICTWEET_FB_SECRET']

環境変数を登録。APP_ID, SECRET_IDはご自身のに置き換えてください。

$ export PICTWEET_FB_ID=APP_ID
$ export PICTWEET_FB_SECRET=SECRET_ID

ルーティングの設定

user.rb
# :omniauthable, omniauth_providers: [:facebook] を追加

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook]
$ rake routes

#↓が追加されていることを確認

user_facebook_omniauth_authorize GET|POST /users/auth/facebook(.:format)          users/omniauth_callbacks#passthru
user_facebook_omniauth_callback GET|POST /users/auth/facebook/callback(.:format) users/omniauth_callbacks#facebook

viewにリンクを設置

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

controllerの設置

ファイルの作成

$ touch app/controllers/omniauth_callbacks_controller.rb

レファレンスからそのままコピペ

app/controllers/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?#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

完成!!!

参考
http://qiita.com/hiyoko/items/3c9a2e2a351fcd5b0698
https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview

10
8
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
10
8