Has somebody done this already? If so, please let me know. I couldn’t find
anything as hands-off as I’d like for managing roles with the
restful_authentication plugin. So I made one.
If you like what you see, why not recommend me on WorkingWithRails?
restful_roles sits on top of restful_authentication like a small child atop his
father’s shoulders. Proud and triumphant, even though most of the accomplishment
isn’t really his.
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.
Add to the user migration, or create a separate one. The important thing is to
create a string field by the name of “role” in your users table.
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 :login_required require_role :admin
This requires Admin or greater privileges to use any action in the controller.
# app/controllers/widgets_controller.rb before_filter :login_required 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.