Project

abilities

0.0
No release in over 3 years
Low commit activity in last 3 years
Authorization dsl to manage permissions in rails.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 0.21

Runtime

~> 5.1
 Project Readme

Gem Version Code Climate Build Status

Authorization

DSL to manage user permissions in Rails.

Why

I want to:

  • Use a DSL instead of a plain class.
  • Limit authorizations to only controllers and their views.

Install

Put this line in your Gemfile:

gem 'chi-authorization'

Then bundle:

$ bundle

Configuration

Generate the policies file:

bin/rails g chi:authorization:install

Set the user helper_name inisde the generated intializers/authorization.rb:

Chi::Authorization.configure do |config|
  config.helper_name = :current_user
end

Usage

Policies

Use can and cannot methods to define the policies inside the generated config/authorization.rb:

Chi::Authorization.define do |current_user|
  can :view, :any
  can :manage, User, if: ->(user) {
    user == current_user
  }

  scope unless: ->{ current_user.admin? } do
    can :detroy, Product
  end
end

Controllers

Using authorize! method Chi::Exceptions::AccessDenied is raised if authorization fails:

class UsersController < ApplicationController
  def edit
    @user = User.find(params[:id])
    authorize! :edit, @user
  end
end

If you don't want an exception to be raised use can? and cannot? instead:

class UsersController < ApplicationController
  def edit
    @user = User.find(params[:id])
    if can?(:edit, @user)
      @user.update user_params
    else
      # handle access denied
    end
  end
end

Views

The helpers can? and cannot? are available in the controller views too:

<% if can?(:detroy, @product) %>
  <%= link_to @product, method: :delete %>
<% end %>

Contributing

Any issue, pull request, comment of any kind is more than welcome!

Credits

This gem is funded and maintained by mmontossi.

With the sponsorship of:

Occam Logo

License

It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.