Wondering what the best approach would be for managing user roles using acl9?
Here's the need:
- Admins should be able to update a user's role.
Here are the issues:
- How can we list all subject roles? :admin, :manager
- To keep the api endpoints RESTful, I would like to pass the role param in the user_controller's update method ideally.
- How can I authorize just for the role property so that, the owner of the user object can still modify their first_name, last_name fields, but not their role field? Only admins are allowed.
I can check for params manually outside of the access_control
block:
def secure_params
if current_user.has_role?(:admin)
params.require(:user).permit(:first_name, :last_name, :role)
else
params.require(:user).permit(:first_name, :last_name)
end
end
but thought I would check and see if there is a cleaner solution.
Lastly, is it possible and wise to use something like RoleTypes.ADMIN
, RoleTypes.MANAGER
instead of :admin
? If so, what's the best way to do this and is that Class accessible throughout a rails app?
The
Role
model is just a normal model, so you can just query this like you would anything else:Generally, you're much better off using a separate controller for performing administration, and put it in the
Admin::
namespace, and usenamespace :admin do
routes, etc..Then in that controller you can use a normal
access_control
block to make sure no one else can get in:So then, yeah, you can set/update a role in a number of ways, but seeing as a user can have many roles it's probably best not to have a single
:role
param, but rather to use:So then in your controller you would have:
Then in your form you can do something like:
Note that I'm assuming you have just simple roles here, not roles on an object, if you have object roles then you'll need something a bit trickier to capture
authorizable_id
andauthorizable_type
for each role, and some way to select the object on which to act.Hopefully you're already answering this one yourself now - by using different controllers for the admin interface and the user's own interface.
No, the symbols are simpler and better, although it's quite common to do something like:
So that you can then use
Role.permitted_roles
to construct an array of checkboxes, or a dropdown, or something like that.