您如何获得在Rails中使用Grape的巫术?

问题描述 投票:0回答:1

您如何在Rails下的Grape中使用基于cookie的经Sorcery身份验证的会话?

我对利用葡萄控制器中的sessioncurrent_user之类的命令感兴趣。

ruby-on-rails session-cookies grape sorcery
1个回答
0
投票

将以下帮助程序添加到您的根API挂载点:

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

包括Sorcery::Controller给了我所有巫术方法(登录,current_user等),但是需要通过帮助程序添加一些缺少的会话方法,以确保巫术是快乐的。请注意,Grape不提供与导轨相同的CookieJar,因此您将无法使用cookies.signed。这对我来说不是问题,但可能对您而言。我研究了调用签名cookie的魔术功能。

© www.soinside.com 2019 - 2024. All rights reserved.