Skip to content

Defining roles and basic permissions

henning-koch edited this page Nov 3, 2010 · 12 revisions

Aegis allows you to define roles and actions. Each action can be allowed or denied for a role.

The suggested place for your permissions is app/models/permissions.rb. The file looks like this:

class Permissions < Aegis::Permissions

  role :guest
  role :user

  action :create_project do
    allow :user
  end

end

This defines two roles and one action create_project. The action is forbidden to guests and allowed to both admins. See Checking permissions

Giving access to everyone

You can allow an action to all roles like this:

action :give_hug do
  allow :everyone
end

If you leave out the role name or :everyone entirely, Aegis also assumes you mean :everyone.

When you’re giving access to everyone, you might find the deny directive useful:

action :update_profile do
  allow :everyone
  deny :guest
end

When multiple directives match for a given action and role, the last matching action defines the result. When no directive matches, the role’s default permission is used. This will usually mean that permission is denied.

Defining permissions that evaluate at runtime

Often permissions have conditions that are evaluated at the time the permission is checked. You can do this by attaching a block to your allow or deny directives:

action :pull_april_fools_prank do
  Date.today.month == 4 and Date.today.day == 1
end

If you need to refer to the user for whom the permission is checked, you can use the implicit user:

action :order_free_sample do
  not user.has_received_free_sample?
end

The block can also take an argument:

action :update_project do |project|
  user.projects.include? project
end

The argument is given when the permission is checked:

project = Project.find(3)
current_user.may_update_project?(project)

Defining multiple things at once

You can define multiple actions with the same rules like this:

action :create_project, :update_project do
  allow :admin
end

You can allow or deny an action to multiple roles at once:

action :show_project do
  allow :guest, :user
end

Defining permissions with resources

Aegis lets you define permissions with resources. If you are used to RESTful routes and controllers you will find this to be much more expressive than defining actions one by one.