With Pundit 2.5, how do you point policies at the right user and policy class when an app uses Rails 8's authentication generator and an admin area?
answer
- pundit_user defaults to current_user
- generator gives Current.user, not current_user
- authorize [:admin, post] finds Admin::PostPolicy
- policy_class on the model or the call
- pundit_reset! after switching users
basics
~10 sOverride pundit_user to return Current.user, since the generator defines no current_user. Pass an array such as [:admin, post] to use Admin::PostPolicy, and call pundit_reset! after impersonating another user, because Pundit memoises its context.
solid answer
~40 sPundit builds every policy with `pundit_user`, which simply calls `current_user`. Rails 8's authentication generator defines no `current_user`; it exposes the user as `Current.user`, so define `pundit_user` to return `Current.user` in `ApplicationController`. For an admin area with different rules, pass a namespace array: `authorize [:admin, post]` uses `Admin::PostPolicy`, `policy_scope([:admin, Post])` uses `Admin::PostPolicy::Scope`, and `authorize` still returns the post. An `AdminController` can override `authorize` and `policy_scope` to prepend `:admin` automatically. To bypass inference entirely, define `policy_class` on the model or pass `policy_class:`. Pundit memoises its context and policies per request, so after switching to another user mid-request, as an impersonation feature does, call `pundit_reset!` (added in 2.5).
code
ruby · 23 linesclass ApplicationController < ActionController::Base
include Authentication # from bin/rails generate authentication
include Pundit::Authorization
private
def pundit_user
Current.user
end
end
class AdminController < ApplicationController
def policy_scope(scope)
super([:admin, scope])
end
def authorize(record, query = nil)
super([:admin, record], query)
end
end
# Admin::PostsController < AdminController
# @post = authorize Post.find(params[:id]) # Admin::PostPolicy#destroy?go deeper
Know that Pundit gets the user from pundit_user, which calls current_user unless you override it.
Wire pundit_user to Current.user for the Rails 8 generator, and use array namespaces, policy_class and headless symbols to pick policies.
Design admin namespaces with a base controller, handle impersonation with pundit_reset!, and authorize jobs with Pundit.authorize.
Decide where extra authorization context belongs, a wrapper user or a better-chosen record, before policies sprawl.
## Where Pundit gets the user Every policy and scope is built as `PolicyClass.new(user, record)`. The `user` comes from one controller hook, `pundit_user`, whose default body is `current_user`. That default suits apps using Devise, which generates `current_user`. Rails 8's **authentication generator** is different. It creates a `Current` model (`ActiveSupport::CurrentAttributes`) with a `session` attribute and `delegate :user, to: :session, allow_nil: true`, plus an `Authentication` concern. There is no `current_user` method, so the first `authorize` call fails with a `NameError`. Pundit's README shows the fix: 1. define `pundit_user` in `ApplicationController`; 2. return `Current.user` from it. `pundit_user` is also the place for **extra context**. Pundit deliberately passes only user and record to policies; when a rule needs more, such as the request's IP or the forum the user is browsing, return a small wrapper object (`UserContext.new(Current.user, request.remote_ip)`) and read its fields in the policies. ## Choosing the policy class Pundit finds the policy from the record through `PolicyFinder`. There are four ways to change the result: | Technique | Lookup result | |---|---| | `authorize post` | `PostPolicy` | | `authorize [:admin, post]` | `Admin::PostPolicy` | | `def self.policy_class = ForumContentPolicy` on the model | `ForumContentPolicy` for every post | | `authorize post, policy_class: ModerationPolicy` | `ModerationPolicy` for this call | | `authorize :dashboard, :show?` | `DashboardPolicy` (a headless policy) | **Namespaces** are the usual answer for an admin area. Moderators in `/admin/posts` may hard-delete and edit any post, while the public `PostPolicy` only lets authors edit their own. Two policies keep both rule sets simple. With an array, `authorize` still returns the last element, the post, so `@post = authorize [:admin, Post.find(params[:id])]` works. Scopes follow the same rule: `policy_scope([:admin, Post])` resolves `Admin::PostPolicy::Scope`. To avoid repeating `:admin` in every action, the README overrides the helpers in a base controller: 1. `class AdminController < ApplicationController`; 2. `def policy_scope(scope) = super([:admin, scope])`; 3. `def authorize(record, query = nil) = super([:admin, record], query)`. ## Headless policies Some pages have no model behind them: a moderation dashboard, a reports screen, a settings page. Pundit handles these with a **headless policy**: `authorize :moderation_dashboard, :show?` looks up `ModerationDashboardPolicy` from the symbol. The policy still takes two constructor arguments; the second is just the symbol. Views use the same lookup with `policy(:moderation_dashboard).show?` to hide the navigation link. This keeps page-level rules in policies too, instead of scattering `if Current.user.admin?` checks through controllers. ## Memoisation and switching users Within one request, Pundit memoises its `Pundit::Context` (holding the user) and every policy and scope it built. That is efficient, but if the user changes during the request, for example an admin **impersonating** a member, every later check would still use the cached admin. Pundit 2.5 added `pundit_reset!`, which clears the context, the policy and scope caches and the verification flags. Call it right after switching users. ## Outside controllers Jobs, mailers and console scripts have no `pundit_user`. Use the module methods with an explicit user: - `Pundit.authorize(user, post, :destroy?)` raises `Pundit::NotAuthorizedError` like the controller helper; - `Pundit.policy!(user, post)` returns the policy or raises `Pundit::NotDefinedError`; - `Pundit.policy_scope!(user, Post)` resolves the scope. ## Mistakes to avoid - Keeping the default `pundit_user` after adopting the generator. - Relying on a `nil` user reaching policies that call methods on it; either handle `nil` or raise in `ApplicationPolicy#initialize` (the README's "closed system"). - Overriding `authorize` in `AdminController` with a signature that drops `policy_class:` when admin code needs it.
- Why does Pundit not let you pass extra arguments to a predicate, and what do you do instead?Its README argues that authorization should depend only on the user and the domain record; needing more usually means the wrong record is being authorized. When context really is needed, such as an IP address, `pundit_user` returns a wrapper object holding the user and that value, and policies read both from `user`.
- An admin impersonates a member, and the next authorize call in the same request still uses admin rules; why?Pundit memoises its context, with the user it was built from, and every policy for the rest of the request. Changing the signed-in user does not clear those caches. Calling `pundit_reset!` (Pundit 2.5) after the switch discards them, so the next check builds policies for the member.
- Pundit finds current_user on its own with the Rails 8 authentication generator
- authorize [:admin, post] returns the namespace array
- Pundit re-reads current_user for every policy in a request
- Pundit lets you pass extra arguments to predicates such as update?(forum)
- Namespaced policies need a separate Pundit initializer
Assumes Pundit 2.5 on Rails 8.1: pundit_reset! was added in Pundit 2.5, and the Rails 8 authentication generator exposes Current.user rather than current_user.