↓↓クリックして頂けると励みになります。
Rails6.1でFacebook認証を実装します。
まずはFacebook for Developersでアカウントを作成しなければなりません。
developers.facebook.com
アカウント、アプリの作成は以下の手順でお願いします。
mrradiology.hatenablog.jp
GemFileに以下の記述を追加します。
記述追加 GemFile(65行目)
gem 'omniauth', '~> 2.1', '>= 2.1.1' gem 'omniauth-facebook', '~> 9.0'
コマンド
bundle
ユーザテーブルにプロバイダー認証のカラムを追加します。
コマンド(2つ)
rails g migration AddFacebookColumsToUser provider:string uid:string image
rails db:migrate
「config\initializers\devise.rb」に以下の記述を追加します。
記述追加 config\initializers\devise.rb(312行目)
「アプリID」と「app secret」はご自分のものを入れて下さい。
# アプリIDとシークレットはご自分のものを入れてください。 config.omniauth :facebook, "ご自分のアプリID", "ご自分のシークレット", scope: 'email', info_fields: 'email,name', image_size: 'large'
「app\models\user.rb」ファイルに以下の記述を追加します。
記述追加 app\models\user.rb(12行目)
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.email = auth.info.email user.password = Devise.friendly_token[0, 20] user.full_name = auth.info.name # ユーザーモデルに名前があると仮定 user.image = auth.info.image # ユーザーモデルに画像があると仮定 user.uid = auth.uid user.provider = auth.provider end end end
記述追加 app\models\user.rb
9行目に「, :omniauthable」の記述も追加しています。
カンマを忘れないようにして下さい。
コードをコピーしてファイルを置き換えてください。
class User < ApplicationRecord has_one_attached :avatar # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :omniauthable validates :full_name, presence: true, length: {maximum: 50} 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.email = auth.info.email user.password = Devise.friendly_token[0, 20] user.full_name = auth.info.name # ユーザーモデルに名前があると仮定 user.image = auth.info.image # ユーザーモデルに画像があると仮定 user.uid = auth.uid user.provider = auth.provider end end end end
「app\controllers」フォルダに「omniauth_callbacks_controller.rb」ファイルを新規作成して下さい。
app\controllers\omniauth_callbacks_controller.rb(新規作成したファイル)
class OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? sign_in_and_redirect @user, event: :authentication # @userがアクティブ化されていない場合 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
「config/initializers」フォルダに、「omniauth.rb」ファイルを新規作成します。
新規作成 【config/initializers/omniauth.rb】
Rails.application.config.middleware.use OmniAuth::Builder do OmniAuth.config.allowed_request_methods = [:post, :get] end
「Facebookでログイン」ボタンをつけます。
「app\views\devise\sessions\new.html.erb」ファイルに以下の記述を追加します。
記述追加 app\views\devise\sessions\new.html.erb
<%= link_to user_facebook_omniauth_authorize_path, class: "btn btn-info w-100" do %> <i class="fa-brands fa-facebook"></i><span style="margin-left: 1rem;">Facebookでログイン</span> <% end %>
「app\views\devise\registrations\new.html.erb」ファイルにも以下の記述を追加します。
記述追加 app\views\devise\registrations\new.html.erb
<%= link_to user_facebook_omniauth_authorize_path, class: "btn btn-info w-100" do %> <i class="fa-brands fa-facebook"></i><span style="margin-left: 1rem;">Facebookで新規登録</span> <% end %>
ルートを追加します。
「config\routes.rb」ファイルの記述を以下のように追加更新します。
追加更新 config\routes.rb(6行目)
devise_for :users, path: '', path_names: {sign_up: 'register', sign_in: 'login', edit: 'profile', sign_out: 'logout'}, controllers: {omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations'}
ブラウザ確認
http://localhost:3000/register
もしFacebookアカウントのメールアドレスがこのテストサイトで登録したメールアドレスと重複している場合は一度「Postico」でユーザを削除してからテストしてください。
Facebook認証でログインするとプロバイダカラムにデータが格納されます。
↓↓クリックして頂けると励みになります。