attr_accessible/security question with rails - what is the best way to deal with this?
I have a question concerning Rails sec开发者_StackOverflow社区urity. Let's say we have User
model, and it has many boolean values for roles, such as admin
, director
, and so on.
An Admin will definitely want to edit these values on forms, so we'll want to use attr_accessible
to let the admin user do this.
Of course, other uses will be able to edit their User model as well - either editing their profile, or when they invite/add new users to the system themselves. In the case of director's, we actually want them to set roles that are "lesser" than director, but we don't want him to be able to set director
or admin
Since we expose these controllers that modify users, wouldn't attr_accessible
allow director
and admin
to be set in this case? This sounds like a very big security hole.
So what is the best way to restrict access?
Set each parameter, one at a time?
Set
admin = false
anddirector = false
on the create/update actions? The simplest solution, but kind of nasty to have this in the controller.Use an if statement to see if that user role can edit those attributes and allow it?
Use rails callbacks?, such as
before_validation
orbefore_save
?Some other declarative solution?
Thanks
The upcoming release of Rails 3.1 (there is a release candidate out at the moment) has a new option to attr_accessible
that will allow you to define a role that can override it at the controller level by passing without_protection => true
.
You can read more about it here: http://www.enlightsolutions.com/articles/whats-new-in-edge-scoped-mass-assignment-in-rails-3-1
And the section about attr_accessible in the rails security guide here: http://edgeguides.rubyonrails.org/security.html#countermeasures
One of these may be of help:
https://github.com/dmitry/attr_accessible_block
https://github.com/thefrontiergroup/scoped_attr_accessible
... allowing you to use role based conditions to determine what attributes can be set.
精彩评论