Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

rails Googleログインを導入したのですがサイトからログアウトされてしまいます 初心者なので説明が下手かもしれません

例)
Ruby on RailsでTwitterのようなWebアプリをつくっています。
https://zenn.dev/batacon/articles/e9b4a88ede2889
この記事を参考にGoogleログインを実装しています。

Googelログイン実装中に問題が発生しました。
解決方法を教えて下さい。

Rails 7.0.3
ruby 3.1.2
Deviseなし

発生している問題・エラー

    def create
        if (user = User.find_or_create_from_auth_hash(auth_hash))
          log_in user
        end
        redirect_to logout_path
    end

Googleでログインするとredirect_to logout_pathこれが邪魔をしてログインすることができません

記事通りにrails newで新しく作ると問題なく動作するのですが、
今作っているサイトに導入しようとするとログインができない状態です。
エラーメッセージは発生していません。

該当するソースコード

gem 'omniauth-google-oauth2'
gem 'omniauth-rails_csrf_protection'
omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2,
        Rails.application.credentials.google[:client_id],
        Rails.application.credentials.google[:client_secret]
end
routes.rb
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'log_out', to: 'sessions#destroy', as: 'log_out'

  resources :sessions, only: %i[create destroy]
sessions_helper.rb
module SessionsHelper
    def current_user
      return unless (user_id = session[:user_id])
  
      @current_user ||= User.find_by(id: user_id)
    end
    
    def log_in(user)
      session[:user_id] = user.id
    end
  
    def log_out
      session.delete(:user_id)
      @current_user = nil
    end
end
sessions_controller.rb
class SessionsController < ApplicationController
    def create
        if (user = User.find_or_create_from_auth_hash(auth_hash))
          log_in user
        end
        redirect_to logout_path
    end
       
    def destroy
        log_out
        redirect_to root_path
    end
    
    private
    
    def auth_hash
        request.env['omniauth.auth']
    end
end
user.rb
  class << self
    def find_or_create_from_auth_hash(auth_hash)
      user_params = user_params_from_auth_hash(auth_hash)
      find_or_create_by(email: user_params[:email]) do |user|
        user.update(user_params)
      end
    end
    
    private

    def user_params_from_auth_hash(auth_hash)
      {
        name: auth_hash.info.name,
        email: auth_hash.info.email,
        image: auth_hash.info.image,
      }
    end
  end

既存のコードが邪魔しているのでしょうか?

最後まで読んでいただきありがとうございます
ご教授いただけると幸いです

0 likes

2Answer

(logout_path ではなく、log_out_path ですね…
routes.rb の記述で as: ‘log_out’ になってるので。)

sessionsコントローラのcreateでのログイン処理で、
最後にlogout_pathにリダイレクトしてるので、
sessions#dedtroyのログアウト処理が走って、
ログアウトしています。

sessionsコントローラのcreateでのログイン処理の
最後でリダイレクトするパスは、ログイン後、
遷移させたいパスにするのが、正解です。

1Like

Your answer might help someone💌