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
endUsage
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
endControllers
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
endIf 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
endViews
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:
License
It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.