【问题标题】:Accessing session parameters in Pundit policy在 Pundit 策略中访问会话参数
【发布时间】:2013-12-03 21:51:17
【问题描述】:

Pundit 策略似乎不访问会话参数。 As 构造不会将会话重新识别为有效的变量或方法。有没有办法访问会话或其他参数?

class MyModelPolicy
  def create?
    @contructs = Construct.where(['id = ?', session[:construct_id]]).all
  end
end

【问题讨论】:

  • 这行代码在哪里?控制器?
  • 抱歉,错过了您的评论。该行将在 ModelName_policy.rb 中。

标签: ruby-on-rails-3.2 pundit


【解决方案1】:

我是 Pundit 的撰稿人。默认情况下,策略只能访问当前用户和您正在检查权限的记录。

您可以使用context pattern defined in the Pundit docs。首先在您的app/model 目录中创建一个用户上下文类,接受您需要的所有上下文参数,在本例中为session

class UserContext
  attr_reader :user, :session

  def initialize(user, session)
    @user = user
    @session = session
  end
end

然后,您可以使用 UserContext 类的实例覆盖 pundit 使用的用户记录。

class ApplicationController
  include Pundit

  def pundit_user
    UserContext.new(current_user, session)
  end
end

通过使您的应用程序策略接受上下文来完成。如果您想遵守旧政策,请将这些方法委托给上下文。

class ApplicationPolicy
  attr_reader :context, :user, :session

  def initialize(context, record)
    @context = context
    @record = record
  end

  delegate :user, to: :context
  delegate :session, to: :context

  ...

end

现在您可以在您的政策中访问session

【讨论】:

  • 如何为范围提供额外的上下文? def index; resources = ContextPolicy::Scope.new(current_user, context).resolve; end 有效,但 after_action :verify_policy_scoped, only: :index 触发 Pundit::PolicyScopingNotPerformedError。我可以让它在 Pundit 的思维方式中发挥作用吗?
  • @dira 如果您为用户使用包装类(在本例中为用户上下文),则该上下文实例将在您的策略范围内可用,就像在授权方法内一样。
  • 您缺少记录的 attr_reader。为答案+1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
相关资源
最近更新 更多