Cannie

Cannie is a gem for authorization/permissions checking.

Installation

Add this line to your application's Gemfile:

gem 'cannie'

And then execute:

$ bundle

Or install it yourself as:

$ gem install cannie

Usage

Define permissions

Permissions are defined in Permissions class, which could be generated by Rails generator:

rails g cannie:permissions

Than you can define all the permissions you want inside ::initialize method of Permissions class:

class Permissions
  include Cannie::Permissions

  def initialize(user)
    if user.admin?
      allow :manage, on: :all
    else
      allow :read, on: Post
      allow :read, on: Comment
      allow :create, on: Comment

      # allow delete comments, that were created only if user has posted those comments
      allow :delete, on: Comment do |*comments|
        comments.all?{|c| c.user_id == user.id}
      end
    end
  end
end

Checking permissions

To be sure that permissions checking is handled in each action of your controller, add check_permissions method call to your controllers:

class PostsController < ApplicationController
  check_permissions

  #...
end

To skip checking permissions for controller, add skip_check_permissions method call:

class PagesController < ApplicationController
  skip_check_permissions

  #...
end

Checking of permissions on per-action basis is done by calling permit! method inside of controller's actions:

class PostsController < ApplicationController
  check_permissions

  def index
    @posts = Posts.all
    permit! :read, on: posts # checks whether user able to read fetched posts
  end
end

Handling of unpermitted access

If user is not permitted for appropriate action, Cannie::ActionForbidden exception will be raised. It can be handled globally by using rescue_from inside ApplicationController:

class ApplicationController < ActionController::Base
  rescue_from Cannie::ActionForbidden do |exception|
    redirect_to root_path, alert: exception.message
  end
end

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request