What is Authorization?
Authorization is a security method used to define user/client privileges and access levels to system resources such as files, services, computer programs, data, and application features. This is the process of allowing or denying access to a network resource depending on the user's identity, which provides the user access to numerous resources.
The majority of web security systems work in two steps. The first stage is authentication, which verifies the user's identification, and the second stage is authorization, which grants the user access to various resources based on the user's identity. To enable application deployment and maintenance, modern operating systems rely on well-designed authorization processes.
Steps to Set up Pundit
-
Add gem pundit to the Gemfile.
-
Incorporate Pundit into the application controller.
-
Execute the command bundle install.
-
Rails g pundit:install can also be used to define an application policy with some useful defaults.
-
In the app/policies/ directory, define the policies.
- After declaring new classes, restart the Rails server so that Rails can take them up.
Pundit Working with Rails
We can use Rails Pundit to define policy classes that manage authorization for various types of documents. Here's an illustration:
Ruby
class PostPolicy
attr_reader :user, :post
def initialize(user, post)
@user = user
@post = post
end
def update?
user.admin?
end
end

You can also try this code with Online Ruby Compiler
Run Code
In this case, the update function in the PostPolicy class examines the user's role and returns a boolean value.
Ruby
class PostsController < ApplicationController
def update
@post = Post.find(params[:id])
authorize @post
@post.update
end
end

You can also try this code with Online Ruby Compiler
Run Code
This is a policy that restricts users from editing posts if they are admins or the post is unpublished.
Pundit Policy Scopes
Assume we have a BlogPost model with a published boolean attribute and we want only admins to have access to unpublished blog posts. In this situation, in the BlogPostPolicy class, we can define a policy scope method that returns only published blog posts for non-admin users, as seen below:
Ruby
class BlogPostPolicy < ApplicationPolicy
# ...
class Scope < Scope
def resolve
if @user.has_role?(:admin)
scope.all
else
scope.where(published: true)
end
end
end
end

You can also try this code with Online Ruby Compiler
Run Code
This policy scope method determines whether the user is an administrator or not and returns all blog posts for administrators and only published blog posts for non-administrators.
Ruby
class BlogPostsController < ApplicationController
def index
@blog_posts = policy_scope(BlogPost).order(created_at: :desc)
authorize @blog_posts
end
end

You can also try this code with Online Ruby Compiler
Run Code
The policy_scope function, in this case, returns the authorized subset of blog posts based on the policy scope defined in the BlogPostPolicy class, while the authorize method verifies that the user is authorized to read the subset of blog posts.
We can quickly apply authorization rules to groupings of records within a model using policy scopes, making it easier to manage access control in our application.
Characteristics of Policy Class
-
The policy name should always begin with the name of the model to which it belongs and end with the Policy.
-
The policy's initialize method would require the instance variable user and the model to be permitted. On the other hand, if the model is simply another object that we want to authorize, we can get by. Consider a service or form object that has requirements that must be met in order for the controller action to be performed.
- The method names should correspond to controller actions denoted by a?. So, for controller actions such as new, create, edit, and so on, the policy methods new?, create?, edit?, and so on must be defined.
Frequently Asked Questions
What is Rails Migration?
A Rails migration is a tool for changing the database structure of an application. Instead of dealing with SQL scripts, a domain-specific language (DSL) is used to specify database changes. Because the code is database-independent, you may quickly migrate your project to a new platform. Migrations can be rolled back and maintained alongside the source code of your application.
What is Flash?
Flash is a one-of-a-kind hash (a mechanism that operates like a hash) that only exists between queries. It is analogous to a session hash that self-destructs once accessed. It is widely used to transmit messages from the controller to the display in order for the user to receive success and failure notifications after submitting forms.
What are the strong parameters in Rails?
Strong Parameters, also known as Strong Params, are used in many Rails projects to strengthen the security of data given via forms. Strong parameters can be used by developers to control which parameters are accepted and used by the controller.
What is a session?
When a user logs in, a sort of cookie known as a session cookie is used to keep data about the user. Access to this information may be granted later on the server. The primary distinction between a session and a cookie is that the former store's specific information about the user, while the latter stores data from all of your browsers collectively.
Conclusion
Pundit is one of the gems for permission management that is fairly powerful, easy to implement, does not take long to install, configure, and has comprehensive documentation. It provides a versatile and user-friendly method for configuring authorization policies and policy scopes using PORC. This article shows you the method of using Pundit Gem for Authorization in Rails, along with the various policies present in Pundit.
To better understand the topic, you can refer to Forms in Ruby on Rails, Sessions, cookies and Authentication in Ruby on Rails, and Working with Forms - Basics in Ruby on Rails.
For more information, refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Python, Data Structures and Algorithms, Competitive Programming, System Design, and many more!
Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!