PressingOnAlways
PressingOnAlways

Reputation: 12366

How do you get Sorcery working with Grape in Rails?

How can you use a cookies based Sorcery authenticated session in Grape under Rails?

I am interested in utilizing commands like session and current_user from a grape controller.

Upvotes: 1

Views: 274

Answers (1)

PressingOnAlways
PressingOnAlways

Reputation: 12366

Add the following helpers to your root API mount point:

class API < Grape::API
  ..
  helpers APIHelpers
  ..
end
# add this to app/api/api_helpers.rb
module APIHelpers
  include Sorcery::Controller
  def session
    env['rack.session']
  end

  def reset_session
    if env['rack.session']&.respond_to?(:destroy)
      session.destroy
    else
      env['rack.session'] = {}
    end
  end

  def form_authenticity_token
    session[:_csrf_token] ||= SecureRandom.base64(32)
  end

  def current_user
    @current_user = login_from_session || nil unless defined?(@current_user)
    @current_user
  end
end

Including Sorcery::Controller gave me all the sorcery methods (login, current_user, etc), but there were a few missing session methods that needed to be added via the helpers to make sure sorcery was happy. Note, Grape does not provide the same CookieJar as rails, so you won't be able to utilize cookies.signed. This was not an issue for me, but it may be for you. I worked around the sorcery functions that would call a signed cookie.

Upvotes: 1

Related Questions