Authorization With Pundit

Pundit is a tool that allows you to restrict certain parts of your Rails application to authorized users. It does this by providing you with certain helpers.

In this tutorial, you will build a blog that restricts parts such as creating, updating and deleting articles to authorized users only.

Getting Started

Start by generating a new Rails application.

rails new pundit-blog -T

The -T flag tells Rails to generate the new application without the default test suite. Running the command will generate your Rails application and install the default gems.

Go ahead and add the following gems to your Gemfile. You will be using bootstrap-sass for the layout of your application, and Devise will handle user authentication.

#Gemfile  ... gem 'bootstrap-sass' gem 'devise'

Run the command to install the gem.

bundle install

Now rename app/assets/stylesheets/application.css to app/assets/stylesheets/application.scss. Add the following lines of code to import bootstrap.

#app/assets/stylesheets/application.scss  ... @import 'bootstrap-sprockets'; @import 'bootstrap';

Create a partial named _navigation.html.erb to hold your navigation code; the partial should be located in app/views/layouts directory. Make the partial look like what I have below.

#app/views/layouts/_navigation.html.erb  <nav class="navbar navbar-inverse">   <div class="container">     <div class="navbar-header">       <%= link_to 'Pundit Blog', root_path, class: 'navbar-brand' %>     </div>     <div id="navbar">       <ul class="nav navbar-nav pull-right">       <li><% link_to 'Home', root_path %></li>       <ul class="nav navbar-nav pull-right">         <% if user_signed_in? %>         <li><%= current_user.email %></li>         <li><%= link_to 'Log out', destroy_user_session_path, method: :delete %></li>         <% else %>           <li><%= link_to 'Log In', new_user_session_path %></li>           <li><%= link_to 'Sign Up', new_user_registration_path %></li>         <% end %>       </ul>     </ul>   </div> </nav>

For the navigation to be used, you need to render it in your application layout. Tweak your application layout to look like what I have below.

#app/views/layouts/application.html.erb  <!DOCTYPE html> <html>   <head>     <title>Pundit-Blog</title>     <%= csrf_meta_tags %>      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>     <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>   </head>    <body>     <%= render "layouts/navigation" %>     <div id="flash">       <% flash.each do |key, value| %>         <div class="flash <%= key %>"><%= value %></div>       <% end %>     </div>     <div class="container-fluid">       <%= yield %>     </div>   </body> </html>

Generate the User Model

Run the command to install Devise.

rails generate devise:install

Now generate your User model.

rails generate devise User

Migrate your database.

rake db:migrate

Generate Article Resources

Run the command to generate your Article resources.

rails generate scaffold Articles title:string body:text

This will generate your ArticlesController and Article Model. It will also generate the views needed.

Now migrate your database by running:

rake db:migrate

Open up app/views/articles/_form.html.erb and make it look like what I have below.

#app/views/articles/_form.html.erb  <%= form_for(article) do |f| %>   <% if article.errors.any? %>     <div id="error_explanation">       <h2><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h2>        <ul>       <% article.errors.full_messages.each do |message| %>         <li><%= message %></li>       <% end %>       </ul>     </div>   <% end %>    <div class="field">     <%= f.label :title %>     <%= f.text_field :title %>   </div>    <div class="field">     <%= f.label :body %>     <%= f.text_area :body %>   </div>    <div class="actions">     <%= f.submit %>   </div> <% end %>

For your index file, it should look like this.

#app/views/articles/index.html.erb  <table class="table table-bordered table-striped table-condensed table-hover">   <thead>   <tr>     <th>Title</th>     <th>Body</th>     <th colspan="3"></th>   </tr>   </thead>    <tbody>     <% @articles.each do |article| %>     <tr>       <td><%= article.title %></td>       <td><%= article.body %></td>       <td><%= link_to 'Show', article %></td>       <td><%= link_to 'Edit', edit_article_path(article) %></td>       <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>     </tr>     <% end %>   </tbody> </table>  <br>  <%= link_to 'New article', new_article_path %>

The above code arranges the articles on the index page into a table format to make it look presentable.

Open up your routes file and add the route for articles resources.

#config/routes.rb  ...   resources :articles   root to: "articles#index"

Integrate Pundit

Add the Pundit gem to your Gemfile.

#Gemfile  ... gem 'pundit'

Run the command to install.

bundle install

Integrate Pundit to your application by adding the following line to your ApplicationController.

#app/controllers/application_controller.rb  ...   include Pundit ...

Run Pundit’s generator.

rails g pundit:install

This will generate an app/policies folder which contains a base class with policies. Each policy is a basic Ruby class.

This is how the base class policy looks.

#app/policies/application_policy.rb  class ApplicationPolicy   attr_reader :user, :record    def initialize(user, record)     @user = user     @record = record   end    def index?     false   end    def show?     scope.where(:id => record.id).exists?   end    def create?     false   end    def new?     create?   end    def update?     false   end    def edit?     update?   end    def destroy?     false   end    def scope     Pundit.policy_scope!(user, record.class)   end    class Scope     attr_reader :user, :scope      def initialize(user, scope)       @user = user       @scope = scope     end      def resolve       scope     end   end end

Create the Article Policy

Now you need to write your own policy. For this tutorial, you want to allow only registered users to create new articles. In addition to that, only creators of an article should be able to edit and delete the article.

To achieve this, your article policy will look like this.

#app/policies/article_policy.rb  class ArticlePolicy < ApplicationPolicy   def index?     true   end    def create?     user.present?   end    def update?     return true if user.present? && user == article.user   end    def destroy?     return true if user.present? && user == article.user   end    private      def article       record     end end

In the above, you are permitting everyone (registered and non-registered users) to see the index page. To create a new article, a user has to be registered. You use user.present? to find out if the user trying to perform the action is registered.

For updating and deleting, you want to make sure that only the user who created the article is able to perform these actions.

At this point, you need to establish a relationship between your Article and User model.

You do so by generating a new migration.

rails generate migration add_user_id_to_articles user:references

Next, migrate your database by running the command:

rake db:migrate

Open the User model and add the line that seals the relationship.

#app/models/user.rb  ...   has_many :articles

Your Article model should have this.

#app/models/article.rb  ...   belongs_to :user

Now you need to update your ArticlesController so it is in sync with what you have done so far.

#app/controllers/articles_controller.rb  class ArticlesController < ApplicationController   before_action :set_article, only: [:show, :edit, :update, :destroy]    # GET /articles   # GET /articles.json   def index     @articles = Article.all     authorize @articles   end    # GET /articles/1   # GET /articles/1.json   def show   end    # GET /articles/new   def new     @article = Article.new     authorize @article   end    # GET /articles/1/edit   def edit   end    # POST /articles   # POST /articles.json   def create     @article = Article.new(article_params)     @article.user = current_user     authorize @article      respond_to do |format|       if @article.save         format.html { redirect_to @article, notice: 'Article was successfully created.' }         format.json { render :show, status: :created, location: @article }       else         format.html { render :new }         format.json { render json: @article.errors, status: :unprocessable_entity }       end     end   end    # PATCH/PUT /articles/1   # PATCH/PUT /articles/1.json   def update     respond_to do |format|       if @article.update(article_params)         format.html { redirect_to @article, notice: 'Article was successfully updated.' }         format.json { render :show, status: :ok, location: @article }       else         format.html { render :edit }         format.json { render json: @article.errors, status: :unprocessable_entity }       end     end   end    # DELETE /articles/1   # DELETE /articles/1.json   def destroy     @article.destroy     respond_to do |format|       format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }       format.json { head :no_content }     end   end    private     # Use callbacks to share common setup or constraints between actions.     def set_article       @article = Article.find(params[:id])       authorize @article     end      # Never trust parameters from the scary internet, only allow the white list through.     def article_params       params.require(:article).permit(:title, :body, :user_id)     end end

At this point in your application, you have successfully implemented the policies that restrict certain parts of your application to selected users.

You want to add a standard error message that shows whenever a non-authorized user tries to access a restricted page. To do so, add the following to your ApplicationController.

#app/controllers/application_controller.rb  ...   rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized    private      def user_not_authorized       flash[:warning] = "You are not authorized to perform this action."       redirect_to(request.referrer || root_path)     end

This code simply renders a basic text that tells the user s/he is not authorized to perform the action.

Run:

$ rails server

To start your Rails server, point your browser to http://localhost:3000 to see what you have.

Conclusion

In this tutorial, you learned how to work with both Devise and Pundit. You were able to create policies that allowed only authorized users to view certain parts of the application. You also created a basic error text that shows when a non-authorized user tries to access a restricted part of the application.

You can learn more about Pundit by checking the GitHub page.

You may also like...