Minimal authorization through OO design and pure Ruby classes
Minimal authorization through OO design and pure Ruby classes
Pundit provides a set of helpers which guide you in leveraging regular Ruby classes and object oriented design patterns to build a straightforward, robust, and scalable authorization system.
Pundit is built and maintained by Varvet, a digital product studio in Sweden. Jonas Nicklas first released it in 2012, and Varvet has kept it small and sharp ever since: one tool that does one thing well. Over 100 million downloads, used by 38,000+ repositories on GitHub.
It started as a pattern we wrote up in Simple authorization in Ruby on Rails apps. We build Ruby on Rails products from our studio in Sweden. If you want the team behind Pundit in the room, we're at varvet.com.
Please note that the README on GitHub is accurate with the latest code on GitHub. You are most likely using a released version of Pundit, so please refer to the documentation for the latest released version of Pundit.
bundle add punditInclude Pundit::Authorization in your application controller:
class ApplicationController < ActionController::Base
include Pundit::Authorization
endOptionally, you can run the generator, which will set up an application policy with some useful defaults for you:
rails g pundit:installAfter generating your application policy, restart the Rails server so that Rails
can pick up any classes in the new app/policies/ directory.
Pundit is focused around the notion of policy classes. We suggest that you put
these classes in app/policies. This is an example that allows updating a post
if the user is an admin, or if the post is unpublished:
class PostPolicy
attr_reader :user, :post
def initialize(user, post)
@user = user
@post = post
end
def update?
user.admin? || !post.published?
end
endAs you can see, this is a plain Ruby class. Pundit makes the following assumptions about this class:
current_user method to retrieve what to send into this argumentupdate?.
Usually, this will map to the name of a particular controller action.That's it really.
Usually you'll want to inherit from the application policy created by the generator, or set up your own base class to inherit from:
class PostPolicy < ApplicationPolicy
def update?
user.admin? or not record.published?
end
endIn the generated ApplicationPolicy, the model object is called record.
Supposing that you have an instance of class Post, Pundit now lets you do
this in your controller:
def update
@post = Post.find(params[:id])
authorize @post
if @post.update(post_params)
redirect_to @post
else
render :edit
end
endThe authorize method automatically infers that Post will have a matching
PostPolicy class, and instantiates this class, handing in the current user
and the given record. It then infers from the action name, that it should call
update? on this instance of the policy. In this case, you can imagine that
authorize would have done something like this:
unless PostPolicy.new(current_user, @post).update?
raise Pundit::NotAuthorizedError, "not allowed to PostPolicy#update? this Post"
endYou can pass a second argument to authorize if the name of the permission you
want to check doesn't match the action name. For example:
def publish
@post = Post.find(params[:id])
authorize @post, :update?
@post.publish!
redirect_to @post
endYou can pass an argument to override the policy class if necessary. For example:
def create
@publication = find_publication # assume this method returns any model that behaves like a publication
# @publication.class => Post
authorize @publication, policy_class: PublicationPolicy
@publication.publish!
redirect_to @publication
endIf you don't have an instance for the first argument to authorize, then you can pass
the class. For example:
Policy:
class PostPolicy < ApplicationPolicy
def admin_list?
user.admin?
end
endController:
def admin_list
authorize Post # we don't have a particular post to authorize
# Rest of controller action
endauthorize returns the instance passed to it, so you can chain it like this:
Controller:
def show
@user = authorize User.find(params[:id])
endYou can easily get a hold of an instance of the policy through the policy
method in both the view and controller. This is especially useful for
conditionally showing links or buttons in the view:
<% if policy(@post).update? %>
<%= link_to "Edit post", edit_post_path(@post) %>
<% end %>Given there is a policy without a corresponding model / ruby class, you can retrieve it by passing a symbol.
# app/policies/dashboard_policy.rb
class DashboardPolicy
attr_reader :user
# `_record` in this example will be :dashboard
def initialize(user, _record)
@user = user
end
def show?
user.admin?
end
endNote that the headless policy still needs to accept two arguments. The
second argument will be the symbol :dashboard in this case, which
is what is passed as the record to authorize below.
# In controllers
def show
authorize :dashboard, :show?
...
end# In views
<% if policy(:dashboard).show? %>
<%= link_to 'Dashboard', dashboard_path %>
<% end %>Often, you will want to have some kind of view listing records which a particular user has access to. When using Pundit, you are expected to define a class called a policy scope. It can look something like this:
class PostPolicy < ApplicationPolicy
class Scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.admin?
scope.all
else
scope.where(published: true)
end
end
private
attr_reader :user, :scope
end
def update?
user.admin? or not record.published?
end
endPundit makes the following assumptions about this class:
Scope and is nested under the policy class.current_user method to retrieve what to send into this argument.ActiveRecord::Relation, but it could be something else entirely.resolve, which should return
some kind of result which can be iterated over. For ActiveRecord classes,
this would usually be an ActiveRecord::Relation.You'll probably want to inherit from the application policy scope generated by the generator, or create your own base class to inherit from:
class PostPolicy < ApplicationPolicy
class Scope < ApplicationPolicy::Scope
def resolve
if user.admin?
scope.all
else
scope.where(published: true)
end
end
end
def update?
user.admin? or not record.published?
end
endYou can now use this class from your controller via the policy_scope method:
def index
@posts = policy_scope(Post)
end
def show
@post = policy_scope(Post).find(params[:id])
endLike with the authorize method, you can also override the policy scope class:
def index
# publication_class => Post
@publications = policy_scope(publication_class, policy_scope_class: PublicationPolicy::Scope)
endIn this case it is a shortcut for doing:
def index
@publications = PublicationPolicy::Scope.new(current_user, Post).resolve
endYou can, and are encouraged to, use this method in views:
<% policy_scope(@user.posts).each do |post| %>
<p><%= link_to post.title, post_path(post) %></p>
<% end %>When you are developing an application with Pundit it can be easy to forget to
authorize some action. People are forgetful after all. Since Pundit encourages
you to add the authorize call manually to each controller action, it's really
easy to miss one.
Thankfully, Pundit has a handy feature which reminds you in case you forget.
Pundit tracks whether you have called authorize anywhere in your controller
action. Pundit also adds a method to your controllers called
verify_authorized. This method will raise an exception if authorize has not
yet been called. You should run this method in an after_action hook to ensure
that you haven't forgotten to authorize the action. For example:
class ApplicationController < ActionController::Base
include Pundit::Authorization
after_action :verify_authorized
endLikewise, Pundit also adds verify_policy_scoped to your controller. This
will raise an exception similar to verify_authorized. However, it tracks
if policy_scope is used instead of authorize. This is mostly useful for
controller actions like index which find collections with a scope and don't
authorize individual instances.
class ApplicationController < ActionController::Base
include Pundit::Authorization
after_action :verify_pundit_authorization
def verify_pundit_authorization
if action_name == "index"
verify_policy_scoped
else
verify_authorized
end
end
endThis verification mechanism only exists to aid you while developing your
application, so you don't forget to call authorize. It is not some kind of
failsafe mechanism or authorization mechanism. You should be able to remove
these filters without affecting how your app works in any way.
Some people have found this feature confusing, while many others
find it extremely helpful. If you fall into the category of people who find it
confusing then you do not need to use it. Pundit will work fine without
using verify_authorized and verify_policy_scoped.
If you're using verify_authorized in your controllers but need to
conditionally bypass verification, you can use skip_authorization. For
bypassing verify_policy_scoped, use skip_policy_scope. These are useful
in circumstances where you don't want to disable verification for the
entire action, but have some cases where you intend to not authorize.
def show
record = Record.find_by(attribute: "value")
if record.present?
authorize record
else
skip_authorization
end
endSometimes you might want to explicitly declare which policy to use for a given class, instead of letting Pundit infer it. This can be done like so:
class Post
def self.policy_class
PostablePolicy
end
endAlternatively, you can declare an instance method:
class Post
def policy_class
PostablePolicy
end
endPundit is a very small library on purpose, and it doesn't do anything you can't do yourself. There's no secret sauce here.
`permit` passes both `to` and `not_to` when a `permissions` group names no permissions
[Request] Generate policy file when using scaffolding
Adjust policy-lookup behaviour (e.g. always use same policy class)
Here we go again: Custom error messages?
Per-query level verify_pundit_policy_scoped
Split this into two methods?
Add `policy_class` parameter to `permitted_attributes` function
Overriding both authorize and policy is required for namespacing
Getting a scope for a specific action