This version of Restful Roles was forked from https://github.com/bellmyer/restful_roles
Quite simply, restful_roles is the easiest roles management you can possibly have.
It assumes that your roles are sequentially more permissive. So if you have
member, admin, and owner roles, admins can see all the member stuff, and owners
can see everything.
Your role based objects need to have an accessible “role” property. If you want, you can use the migration below, or you can create custom properties as per your integration if you prefer.
class AddRoletoUser < ActiveRecord::Migration def self.up add_column :users, :role, :string end def self.down remove_column :users, :role, :string end end
Add this to the model that is using restful_authentication:
# app/models/user.rb has_roles "member", "admin", "owner"
Any users you create will be the first role by default – :member in this case.
Roles get more exclusive from left to right.
Now you can do this:
current_user.admin?
and it will return true only if the user’s role is admin OR HIGHER. Therefore, if your lowest role is :member, it would be pointless to call:
current_user.member?
because every user would be at least a member, and it would always return true.
You can add role requirements to any controllers that use require_login.
require_role accepts a role, and an optional :only list.
Of course, you have to be a logged-in user to have a role, and so if you don’t
require_login for an action, then the role checking will never happen for that
action. It works by hooking into restful_authentication’s authorized? method.
# app/controllers/widgets_controller.rb before_filter :authorize require_role "admin"
This requires Admin or greater privileges to use any action in the controller.
# app/controllers/widgets_controller.rb before_filter :if you prefer require_role "member", :only=>[:index, :show] require_role "admin", :only=>[:new, :create, :edit, :update] require_role "owner"
In this case, you have to be at least a Member to see index/show pages, at
least an Admin to see those plus the creation/updating pages, and only Owners
can do anything else.
# app/controllers/widgets_controller.rb before_filter :login_required require_role "admin", :except=>[:index, :show]
The above example requires Admin or greater privileges for everything except the
harmless (in this case) index and show actions.
CAVEAT: the :except option trumps all else, so there’s no reason (or ability) to
combine it with other require_role calls. Doing so would make the developer’s
intentions unclear anyway, and the whole point of this plugin is simplicity.