このページは原文を AI が翻訳したものです。
この記事では、Deviseを使わずに、Railsの標準認証システムの上にOmniAuthを使ってRails 8でGoogleログインを実装する方法を見ていきます。
基本認証を作成する
認証を生成する
Rails 8には認証ジェネレータが付属しており、これを利用できます。UserモデルとSessionモデル、そしてアプリケーションにログインするために必要なコントローラとビューが作成されます。詳細は公式ガイドをご覧ください。
bin/rails generate authenticationパスワードを削除する
Googleログインのみを有効にして、他のログイン方法を削除したいからです。そのため、データベースにusers.password_digestカラムを保持する必要はなく、関連ファイルも削除します。
[timestamp]_create_users.rbからt.string :password_digest, null: falseを削除し、Userモデルを更新してhassecurepasswordの行を削除しましょう。もう必要ないからです。
マイグレーションを実行する
次に、データベースをマイグレーションしてUserテーブルとSessionテーブルを追加します。
bin/rails db:migrateGoogleログインを実装する
OmniAuthのGemを追加する
Gemfileに必要なGemを追加し、bundle installを実行してGemをインストールします。
# OmniAuth and Google OAuth
gem "omniauth", "~> 2.1"
gem "omniauth-google-oauth2", "~> 1.2"
gem "omniauth-rails_csrf_protection", "~> 1.0"OmniAuthを設定する
OmniAuth用のイニシャライザを作成します:
touch config/initializers/omniauth.rb次に、以下の設定を追加します。
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
endデプロイ設定でGOOGLECLIENTIDとGOOGLECLIENTSECRETの環境変数が設定されていることを確認してください。Google OAuth公式ドキュメントを読んで、GOOGLE_CLIENT_IDとGOOGLE_CLIENT_SECRETの値を取得する方法を学んでください。
SocialAccountモデルを作成する
この記事ではGoogleログインのみを実装する必要がありますが、後でGitHubログインなどの他のログイン方法を追加するかもしれないので、ソーシャルアカウント情報を別のモデルに保存する方が良いでしょう。この場合、それはSocialAccountと呼ばれます。
rails generate model SocialAccount user:references provider:string uid:string auth_data:json次に、生成されたモデルを次のように更新します:
class SocialAccount < ApplicationRecord
belongs_to :user
validates :provider, presence: true
validates :uid, presence: true, uniqueness: { scope: :provider }
def self.from_omniauth(auth)
social_account = find_or_initialize_by(provider: auth.provider, uid: auth.uid)
unless social_account.persisted?
user = User.find_or_create_by!(email_address: auth.info.email) do |u|
u.name = auth.info.name
u.avatar_url = auth.info.image
end
social_account.user = user
social_account.save!
end
social_account
end
endメールアドレスでUserを作成または検索するための関数self.from_omniauthを追加します。
ルートとSessionsControllerを更新する
次に、config/routes.rbファイルにOAuthルートを追加する必要があります。
get "/auth/:provider/callback", to: "sessions#create"
get "/auth/failure", to: "sessions#failure"次に、SessionsControllerを更新します。
class SessionsController < ApplicationController
def create
auth = request.env["omniauth.auth"]
social_account = SocialAccount.from_omniauth(auth)
start_new_session_for social_account.user
redirect_to after_authentication_url
end
def failure
redirect_to root_path, alert: "Authentication failed, please try again."
end
endGoogleログインボタンを追加する
sessions/new.html.erbにGoogleログインボタンを追加します:
<%= button_to "Sign in with Google",
"/auth/google_oauth2",
method: :post,
class: "btn btn--primary btn--block",
data: { turbo: false } %>これで、RailsアプリケーションにGoogleログインを正常に追加できました。
まとめ
この設定により、Deviseを使わずにRailsアプリケーションにGoogleログインを実装できます。OmniAuthを使えば、FacebookやGitHubなどの他のプロバイダーにも対応するようにアプリケーションを拡張できます。


コメントを読み込み中…