How to restrict foreign keys in Rails' update controller action?
In my Rails app I have invoices which in turn can have many projects.
model:
class Invoice < ActiveRecord::Base
attr_accessible :project_id
end
controller:
class InvoicesController < ApplicationController
before_filter :authorized_user, :only => [ :show, :edit, :destroy ]
before_filter :authorized_project, :only => [ :create, :update ]
def create # safe
@invoice = @project.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to edit_invoice_path(@invoice)
else
render :new
end
end
def update # not safe yet
if @invoice.update_attributes(params[:invoice])
flash[:success] = "Invoice updated."
redirect_to edit_invoice_path(@invoice)
else
render :edit
end
end
private
def authorized_user
@invoice = Invoice.find(params[:id])
redirect_to root_path unless current_user?(@invoice.user)
end
def authorized_project
@project = Project.find(params[:invoice][:project_id])
redirect_to root_path unless current_user?(@project.user)
end
end
My biggest concern is that a malicious user might, one day, create an
invoice that belongs to the project of another user.
Now thanks to the help of some people on this board I managed to come up
with a before_filter that makes sure that this won't happen when a project
is created.
The problem is I don't understand how to apply this filter to the update
action as well.
Since the update action does not make use of Rails' build function, I
simply don't know how to get my @project in there.
Can anybody help?
No comments:
Post a Comment