Skip to content
/ permisi Public

Simple and dynamic role-based access control for Rails

License

Notifications You must be signed in to change notification settings

ukazap/permisi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

If you're viewing this at https://github.com/ukazap/permisi, you're reading the documentation for the main branch. Go to specific version.

Permisi

Simple and dynamic role-based access control for Rails

Gem Version

Concept

Permisi provides a way of dynamically declaring user rights (a.k.a. permissions) using a simple role-based access control scheme.

This is not an alternative to CanCanCan/Pundit, instead it complement them with dynamic role definition and role membership.

Permisi has three basic concepts:

  • Actor: a person, group of people, or an automated agent who interacts with the app
  • Role: a job function, job title, or rank which determines an actor's authority
  • Permission: the ability to perform an action

Installation

Add this line to your application's Gemfile:

gem 'permisi'

And then execute:

$ bundle install
$ rails g permisi:install

Configuring backend

Set config.backend in the initializer to the backend of choice for storing and retrieving roles:

# config/initializers/permisi.rb

Permisi.init do |config|
  #...
  config.backend = :active_record
  #...
end

To use :active_record, run the generated migration from the installation step:

$ rails db:migrate

Permisi only support :active_record backend at the moment. In the future, it will be possible to use :mongoid.

Configuring permissions

First you have to predefine the permissions, which is basically a set of possible actions according to the app's use cases. The actions can be grouped in any way possible. For example, you might want to define actions around resource types.

To define the available actions in the system, assign a hash to the config.permissions with the following format:

# config/initializers/permisi.rb
Permisi.init do |config|
  # ...
  config.permissions = {
    # A symbol-array pair denotes a namespace.
    # A common use of namespacing is for grouping
    # available actions by resources.
    authors: [
      # Enclosed in the array are symbols
      # denoting available actions in the namespace:
      :list,
      :view,
      :create,
      :edit,
      :delete
    ],
    # You can also use the simplified %i[] notation:
    publishers: %i[list view create edit delete],
    # Besides actions, you can also have nested
    # namespaces:
    books: [
      :list,
      :view,
      :create,
      :edit,
      :delete,
      {
        editions: [
          :list, :view, :create, :edit, :delete, :archive
        ]
      }
    ]
  }
  # ...
end

Defining and managing roles

Once you have the predefined permissions, you can then define different roles with different level of access within the boundary of the predefined permissions. You can delete or create new roles according to organizational changes. You can also modify existing roles without a change in your code.

You can create, edit, and destroy roles at runtime. You might also want to define preset roles via db/seeds.rb.

# Interact with Permisi.roles as you would with ActiveRecord query interfaces:

# List all roles
Permisi.roles.all

# Create a new role
admin_role = Permisi.roles.create(slug: :admin, name: "Administrator", permissions: {
  books: {
    list: true,
    view: true,
    create: true,
    edit: true
  }
})

# Ask specific role permission
admin_role.allows?("books.delete") # == false

# Update existing role
admin_role.permissions[:books].merge!({ delete: true })
admin_role.save
admin_role.allows?("books.delete") # == true

Configuring actors

You can then give or take multiple roles to an actor which will allow or prevent them to perform certain actions in a flexible manner. But before you can do that, you have to wire up your user model with Permisi using via Permisi::Actable mixin.

Permisi does not hold an assumption that a specific model is present (e.g. User model). Instead, it keeps track of "actors" internally. The goal is to support multiple use cases such as actor polymorphism, user groups, etc.

For example, you can map your user model to Permisi's actor model like so:

# app/models/user.rb

class User < ApplicationRecord
  include Permisi::Actable
end

You can then interact using #permisi method:

user = User.find_by_email("esther@example.com")
user.permisi # => instance of Actor

admin_role = Permisi.roles.find_by_slug(:admin)
admin_role.allows?("books.delete") # == true

user.permisi.roles << admin_role

user.permisi.role?(:admin) # == true
user.permisi.has_role?(:admin) # == user.permisi.role? :admin

user.permisi.may_i?("books.delete") # == true
user.permisi.may?("books.delete") # == user.permisi.may_i? "books.delete"

user.permisi.roles.destroy(admin_role)

user.permisi.role?(:admin) # == false
user.permisi.may_i?("books.delete") # == false

Caching

Permisi has several optimizations out of the box: actor roles eager loading, actor permissions memoization, and the optional actor permissions caching.

Actor roles eager loading

Although checking whether an actor has a role goes against a good RBAC practice, it is still possible on Permisi. Calling role? multiple times will only make one call to the database:

user = User.find_by_email("esther@example.com")
user.permisi.role?(:admin) # eager loads roles
user.permisi.role?(:admin) # uses the eager-loaded roles
user.permisi.has_role?(:admin) # uses the eager-loaded roles

Actor permissions memoization

To check whether or not an actor is allowed to perform a specific action (#may_i?), Permisi will check on the actor's permissions which is constructed in the following steps:

  • load all the roles an actor have from the database
  • initialize an empty aggregate hash
  • for each role, merge its permissions hash to the aggregate hash

Deserializing the hashes from the database and deeply-merging them into an aggregate hash can be expensive, so it will only happen to an instance of actor only once through memoization.

Actor permissions caching

Although memoization helps, the permission hash construction will still occur every time an actor is initialized. To alleviate this, we can introduce a caching layer so that we can skip the hash construction for fresh actors. You must configure a cache store to use caching:

# config/initializers/permisi.rb

Permisi.init do |config|
  # You can use the default Rails cache store
  config.cache_store = Rails.cache
  # or use other cache stores
  config.cache_store = ActiveSupport::Cache::RedisCacheStore.new(url: ENV['REDIS_URL'])
  # or
  config.cache_store = ActiveSupport::Cache::FileStore.new("/home/ukazap/permisi_cache/")
end

You can also roll your own custom cache store.

Cache/memo invalidation

The following will trigger actor's permissions cache/memo invalidation:

  • adding roles to the actor
  • removing roles from the actor
  • editing roles that belongs to the actor

Contributing

For development and how to submit improvements, please refer to the contribution guide.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Permisi project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

Simple and dynamic role-based access control for Rails

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks