Checking permissions

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

After you gave your User model a role you can check permissions on user instances. Say you have your permissions configured like this:

class Permissions < Aegis::Permissions
  role :user
  resources :notes do
    allow :user
  end
end

The following checks now return either true or false:

user.may_index_notes?
user.may_show_note?(note)
user.may_update_note?(note)
user.may_create_note?
user.may_destroy_note?(note)

Note how some actions take an argument to provide the required context for the permission check.

Asserting that a permission is granted

Often all you want is to assert that a permission is granted at a given point in your code, without handling the case that the permission is denied. For this Aegis provides a strict way to check permissions, which raise an error unless permission is granted. Note the exclamation mark in the follow example:

user.may_create_note!

The strict check will raise an Aegis::AccessDenied if permission is denied. This way all subsequent code won’t be executed unless the user has the required rights.

Checking if a user has a role

Whenever possible, check for permissions and not for roles. If you positively must query for a role, you can write:

user.has_role?("admin")