Matthew Berman
Matthew Berman

Reputation: 8631

Is creating a new model by passing it params secure?

I have a comment model. I am creating a new instance of that model by passing it params from my view to the comment controller. Here is the comment controller:

class CommentsController < ApplicationController
  def create
    session[:return_to] = request.referrer
    @comment = Comment.create(:user_id  => current_user.id,
                             :issue_id => params[:issue_id],
                             :content  => params[:content])
    redirect_to session[:return_to]
  end
end

Here is how I am passing the params in my view:

<%= link_to "Test Comment", comments_path(:issue_id => @issue.id,
                                          :content  => "HeLLO"),
                            method: :create %>

my question is - is this secure? What prevents someone from changing the params[:issue_id] and commenting on another issue? Is there a better way of doing this?

Upvotes: 1

Views: 140

Answers (1)

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

yeah, there are better ways

at first we look to your controller. to store the referrer and redirect back to it makes no sense (at least you should NOT save this in a session) rails can do this with the key :back.

at second you dont need to make a varaible with the @ because you dont use the created object. and also you dont need to save the restult. just do

class CommentsController < ApplicationController
  def create
    Comment.create(:user=>current_user, :issue_id=>params[:issue_id],:content=> params[:content])
    redirect_to :back
  end
end

++ edit

actually a better way would to to it like this:

class CommentsController < ApplicationController
  def create
    current_user.comments.create(issue_id: params[:issue_id], content: params[:content])
    redirect_to :back
  end
end

just use rails associations

-- edit

and as you think, YES we can change the issue_id and write comments to any issue i want. so if you want to protect from this you have do do a helper before you crate a comment (its just an example)

class CommentsController < ApplicationController
  def create
    issue = Issue.find(params[:issue_id]
    if issue.is_locked? || current_user.cant_write_at_issue(issue)
      return redirect_to :back, :notice=>"You dont have Privilegs"
    end
    issue.comments.create :user=>current_user, :content=>params[:content])
    redirect_to :back :notice=>"Comment was created successfully"
  end
end

is_locked and cant_write_at_issue you need to define in your models. this is just a way how to protect something.

so now we can change the issue ID but you look if the user has access for doing this :-)

Upvotes: 1

Related Questions