- Read Tutorial
Most production applications need to have a robust permission structure, also called app authorization. In this guide we will walk through how to install and configure the Pundit gem which supplies a great interface for integrating a permission structure into any type of Ruby application. I typically prefer to use Pundit over other authorization gems such as CanCan since I'm a big fan of the syntax, which is essentially pure Ruby. Therefore applications that utilize Pundit for authorization make it more straightforward to read and add to.
Before we install the gem I want to clarify the difference between authorization and authentication:
- Authorization - configuring components of an application so only authorized users can access them. For example: Ensuring that only a post creator can edit his/her post.
- Authentication - allowing users to register and securely sign in/out of the application.
Hopefully that explains the clear separation between the two terms, we've also implemented authentication when we installed Devise, and now we're going to start implement authorization.
Installing Pundit
As you may have guessed we'll go to the gem page for Pundit and get the latest stable version and add it to the Gemfile
.
# Gemfile gem 'pundit', '~> 1.1'
After running bundle
we can start integrating Pundit. Since we want to be able to utilize authorization throughout the application we'll begin by calling the module from the ApplicationController
:
# app/controllers/application_controller.rb class ApplicationController < ActionController::Base include Pundit protect_from_forgery with: :exception def current_user super || OpenStruct.new(full_name: 'Guest') end end
Now let's run the generator which will give the application some base case authorization rules:
rails g pundit:install
This will create a directory called policies
and a single file application_policy.rb
inside of it. This generated file contains the abstract class ApplicationPolicy
and sets up some helpful initializers for each of the standard CRUD methods, such as create
and delete
.
That's all we need for the initial setup, in the next lesson we'll walk through the steps for integrating a permission structure for posts
.