11

It appears that Pundit policy does not access session parameters. As constructs does not reconize session as a valid variable or method. Is there any way to access session or other params?

class MyModelPolicy
  def create?
    @contructs = Construct.where(['id = ?', session[:construct_id]]).all
  end
end
zeeraw
  • 5,197
  • 1
  • 21
  • 27
Jerome
  • 5,583
  • 3
  • 33
  • 76

1 Answers1

26

I'm a contributor to Pundit. Policies by default only has access to the current user and the record you're checking permissions for.

You can use the context pattern defined in the Pundit docs. Start with creating a user context class in your app/model directory accepting all the contextual parameters you need, in this case session.

class UserContext
  attr_reader :user, :session

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

Then you can override the user record used by pundit with an instance of your UserContext class.

class ApplicationController
  include Pundit

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

Finish by making your application policy accept the context. If you want to stay compliant with your old policies, delegate those methods to the context.

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

Now you can access session inside your policies.

zeeraw
  • 5,197
  • 1
  • 21
  • 27
  • What about providing additional context to scopes? `def index; resources = ContextPolicy::Scope.new(current_user, context).resolve; end` works but `after_action :verify_policy_scoped, only: :index` triggers `Pundit::PolicyScopingNotPerformedError`. Could I make it work within the Pundit mindset? – dira Mar 16 '15 at 19:58
  • @dira If you use a wrapping class for your user (in this case user context), that context instance will be available inside your policy scope just as it is inside the authorisation methods. – zeeraw Mar 17 '15 at 14:17
  • You're missing the attr_reader for the record. +1 for the answer – Jamesst20 Feb 12 '19 at 13:52