Tsukasa3300
@Tsukasa3300

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

rails APIでのsessionエラー

解決したいこと

sessionメソッドが使えない

例)
reactでfirebaseのGoogle認証をして、railsAPIでその際に発行されたトークンを認証する、ログイン機能を作っています
その際に、sessionメソッドを使ってcurrent_userメソッドを定義したのですが、current_userが作成されません

userのcreateアクションは正常に機能して、ユーザーは作成されています。
推測として、sessionHelperのlogin(user)メソッドが、sessionがなんらかの原因で使えていないため機能していないのだと思います。

解決方法を教えて下さい。

該当するソースコード

app/controllers/session_helper.rbにて
module SessionHelper
    extend ActiveSupport::Concern
  
    def login(user)
      session[:user_id] = user.id
    end
  
    def current_user
      if session[:user_id]
        @current_user ||= User.find_by(id: session[:user_id])   
      end     
    end
end
-----------------------------------------------------


app/controllers/api/v1/users_controller.rbにて
class Api::V1::UsersController < ApplicationController
    require "jwt"
    include SessionHelper

    def index
      user = current_user
      render json: user 
    end

    def create
        # user_infoに、firebaseから発行されたaccess_tokenをデコードした情報(first)を代入する
        user_info = JWT.decode(user_params[:access_token], nil, false).first
        # user_infoのそれぞれのキーの値を、代入する
        name, email, user_id, picture = user_info.values_at("name", "email", "user_id", "picture")

        # その値を持ったuserを生成する
        user = User.new(name:, email:, picture:)
        if user.save
          login(user)
          render json: { user: user }, status: :ok
        elsif User.find(user_id)
          # 複製しているならエラーを出す
          render status: :bad_request
        end
    end

    private

    def user_params
        params.require(:user).permit(:access_token)
    end
end
----------------------------------------------------


app/config/application.rbにて
require_relative "boot"

require "rails/all"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Api
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 7.0
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore
    # Configuration for the application, engines, and railties goes here.
    #
    # These settings can be overridden in specific environments using the files
    # in config/environments, which are processed later.
    #
    # config.time_zone = "Central Time (US & Canada)"
    # config.eager_load_paths << Rails.root.join("extras")

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true
  end
end
--------------------------------------------------------------


app/config/initializers/session_storeにて
Rails.application.config.session_store :cookie_store, key: '_interslice_session'
---------------------------------------------------


app/controllers/application_controller.rbにて
class ApplicationController < ActionController::API
    include ActionController::Cookies
    include SessionHelper
end
------------------------------------------------------



reactにて
 const signUpWithGoogle = async () => {
      await signInWithPopup(auth, googleProvider);

      const token = await getIdToken(auth.currentUser);
      const user = {
        access_token: token,
      };

      await axios.post('http://localhost:3000/api/v1/users', { user }, {
      });
    }; 
----------------------------------------------------------------
0

No Answers yet.

Your answer might help someone💌