この記事では9ステップでfacebookログイン機能を実装できます
前提
・ facebookアカウントを持っている
・ deviseユーザー
以下手順です全部で9ステップ
- 以下のfacebookディベロッパーでappアカウントを作成
(1) 右上の新しいアプリを追加をクリック
APP_IDとAPP_SECRETが生成される。 # 後で使うので覚えておくこと
(2) 新しいプラットフォームを追加→ ウェブサイトを選択 →サイトURLにfacebookログインを使用するURLを入力(以下のは開発環境です)
⚠️ 本番環境で扱うならサイトURLも適宜変更。
(3) gemfileに追加
GemFile
gem "omniauth", '~>1.6' # バージョンは任意で指定
gem "omniauth-facebook", '~> 4.0' # バージョンは任意で指定ください
$ bundle install
(4) userテーブルに3カラムを追加
$ rails g migration AddFieldsToUser provider:string uid:string image:string
$ rake db:migrate
(5)config/initializers/devise.rbに
config/initializers/devise.rb
Devise.setup do |config|
~中略~
最下部に以下を追加
config.omniauth :facebook, 'API_KEY', 'API_SECRET', scope: 'email', info_fields: 'email, name' # ⚠︎API_KEYとAPI_SECRETは(1)手順で作成したものを記述してください(直書きが危険ですので環境変数とかにして置くのが安全です)
end
参考)
http://qiita.com/noraworld/items/bfa80811c9e30b4474af # 環境変数
(6) メソッドを書いていく!モデルとコントローラーに記述
まずはモデルにメソッド追加
models/user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:validatable, :confirmable,
:omniauthable ←ここだけ追加してます
# userがいなければfacebookアカウントでuserを作成するメソッド
def self.from_omniauth(auth)
user = User.where(email: auth.info.email).first
if user
return user
else
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
# userモデルが持っているカラムをそれぞれ定義していく
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name
user.image = auth.info.image
user.uid = auth.uid
user.provider = auth.provider
# 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
end
end
コントローラー
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?
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
(7) viewを用意!
登録ページとログインページに記述
registrations/new.html.erb
<%= link_to "Facebookで会員登録", user_facebook_omniauth_authorize_path %>
sessions/new,html.erb
<%= link_to "Facebookでログイン", user_facebook_omniauth_authorize_path %>
(8) ルーティング設定
routes.rb
Rails.application.routes.draw do
中略
devise_for :users,
path: '',
path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
controllers: {omniauth_callbacks: 'omniauth_callbacks'}
end
(9) アイコン設定
application_helper.rb
module ApplicationHelper
def avatar_url(user)
if user.image
"http://graph.facebook.com/#{user.uid}/picture?type=large" # facebookの画像があった場合
else
# 代替の何かを返す
end
end
end
これで完了です
localhost:3000/registrationにアクセスしてください
facebookログイン参考)
https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview