Good practice protecting methods

As a ROR developer for newbies, I thought about ways to protect certain methods to make sure that the right user is updating their own content. Here is an example of my approach.

Do you recommend a cleaner way or a better way to accomplish 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 was successfully 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
+3
source share
3 answers

You can use a gem such as declarative_authorization to do this. If you want to do it yourself, I would recommend just drying your code a 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 was successfully 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.") and return
    end
  end
end

, , , , , , /. :

def update
  @owner = Owner.find(session[:owner_id])
  @property = @owner.properties.find(params[:id])
  redirect_to unauthorized_page and return if @property.nil?
end

, , , [: owner_id], . , , [: owner_id], . before_filter, .

0

, . :

class FoosController < ApplicationController
  before_filter :find_user

  def create
    @foo = @user.foos.build
  end

  def update
    @foo = @user.foos.find(params[:id])
  end

  private

  def find_user
    @user = User.find(session[:current_user_id])
  end
end

, : Foo, @user. , , , , , , .

+4

Consider using the discussed method here .

Add an association within the user model and query properties only through this association.

property = Property.find(params[:id])
# vs
property = current_user.properties.find(params[:id])
0
source

Source: https://habr.com/ru/post/1795639/


All Articles