ruby-on-railsgraphqlsession-cookieslogout

How to destroy the current user session from rails through graphql mutation


I am trying to clear user sessions through a graphql mutation which takes user_id as an argument and destroys the user session and sends a message, which will further be used by frontend to sign out.

  argument :user_id, ID, required: true
  field :message, String, null: true

  def resolve(user_id:)
    user = User.find_by(id: user_id)
    raise GraphQL::ExecutionError, 'User not found.' unless user.present?
    destroy_user_session(user_id)
    user.save!
    { message: 'User session cleared'}
  end
  
  private

  def destroy_user_session(user_id)
    binding.pry
    session = context[:session]
    session.clear
    raise GraphQL::ExecutionError, 'Failed to clear session.' unless session.empty?
  end
end

But the problem is, the user session is not getting destroyed properly here. I am testing it using localhost:3000/api/graphql where I call the mutation first and then calls some other query that are accessible once the user is logged in and unfortunately both are being called instead of throwing error like authorization is requried. I tried several steps from different sites but still got stuck here.


Solution

  • Since your graphql_controller is inheriting from application_controller you should have access to sign_out method if you are using devise so if you try calling context[:controller].sign_out it should work

      def destroy_user_session(user_id)
        context[:controller].sign_out
        session = context[:session]
        session.clear
        raise GraphQL::ExecutionError, 'Failed to clear session.' unless session.empty?
      end