ruby on rails - Good practice for protecting methods -
being newbie ror developer i've been thinking of ways of protecting methods make sure correct user updating own content. here example of approach.
would recommend cleaner way or better way of doing such tasks?
# example controller class owner::propertiescontroller < owner::basecontroller def index end etc..... def update @property = property.find(params[:id]) # check correct owner check_owner(:owner_id => @property.owner_id) if @property.update_attributes(params[:property]) redirect_to([:owner, @property], :notice => 'property updated.') else render :action => "edit" end end def destroy @property = property.find(params[:id]) # check correct owner check_owner(:owner_id => @property.owner_id) @property.destroy redirect_to(owner_properties_url) end private def check_owner p = {} if p[:owner_id] != session[:owner_id] redirect_to([:owner, @property], :notice => "property not found.") end end
you use gem declarative_authorization well. if want recommend drying code little bit:
class owner::propertiescontroller < owner::basecontroller before_filter :check_owner, :only => [:update, :destroy] def update if @property.update_attributes(params[:property]) redirect_to([:owner, @property], :notice => 'property updated.') else render :action => "edit" end end def destroy @property.destroy redirect_to(owner_properties_url) end private def check_owner @property = property.find(params[:id] if @property.owner_id != session[:owner_id] redirect_to([:owner, @property], :notice => "property not found.") , return end end end
additionally, can filter properties owner ensure user not owner can not interact properties aren't his/hers. example:
def update @owner = owner.find(session[:owner_id]) @property = @owner.properties.find(params[:id]) redirect_to unauthorized_page , return if @property.nil? end
this forces properties searching ones belong session[:owner_id] instead of entire universe of properties. means properties session[:owner_id] not own not considered. can put code before_filter it's reusable in multiple actions.
Comments
Post a Comment