Form hidden fields and security - ruby-on-rails

I m using hidden field in my app to add user_id to my database "Camping". I have associations "User" has many campings and "Camping" belongs_to "user".
When I run firebug or something like this, I can modify user_id value of this field. If any user puts his ID, I can modify object to other user... I want to avoid this !
My code
<%= f.hidden_field :user_id, :value => current_user.id %>
This code, is necessary because I allow only user to edit / updated / create object if they have user_id == current_user.id.
How to fix this security problem ?
By the way, I m using devise.
Edit with full code
My _form.html.erb
<%= form_for(camping) do |f| %>
<% if camping.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(camping.errors.count, "error") %> prohibited this camping from being saved:</h2>
<ul>
<% camping.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group">
<label for="name">Nom du camping</label>
<%= f.text_field :name, autofocus: true, class:"form-control", id:"name", :required => true%>
</div>
<div class="actions">
<%= f.submit "Enregistrer", class:"btn btn-success" %>
</div>
<% end %>
my controller
def new
#camping = Camping.new
#campings = Camping.all
end
def edit
end
def create
#camping = Camping.new(camping_params)
respond_to do |format|
if #camping.save
format.html { redirect_to #camping, notice: 'Camping was successfully created.' }
format.json { render :show, status: :created, location: #camping }
else
format.html { render :new }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end
def update
#camping = Camping.find(params[:id])
respond_to do |format|
if #camping.update(camping_params)
format.html { redirect_to #camping, notice: 'Camping was successfully updated.' }
format.json { render :show, status: :ok, location: #camping }
else
format.html { render :edit }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end
my edit.html.erb
<div class="containershow">
<h1>Editing Camping</h1>
<%= render 'form', camping: #camping %>
<%= link_to 'Show', #camping %> |
<%= link_to 'Back', campings_path %>
</div>
my new.html.erb
<h1>New Camping</h1>
<%= render 'form', camping: #camping %>
<%= link_to 'Back', campings_path %>
Edit solution ?
User can create and update his camping. I delete hidden_field
def create
# #camping = Camping.new(camping_params)
#camping = Camping.new((camping_params).merge(:user_id => current_user.id))
respond_to do |format|
if #camping.save
format.html { redirect_to #camping, notice: 'Camping was successfully created.' }
format.json { render :show, status: :created, location: #camping }
else
format.html { render :new }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end

In Devise, the current user object is in current_user, available to your controllers. When saving the model, make sure to fill the user id field from that object, and not user input in the update action of your controller. Note that the edit action does not matter, that just renders the edit page, the actual update happens in update (if you follow the default conventions). Of course if you don't want users to even see other users' objects, you also need access control in other controller actions like edit as well, but that (implementing access control in a multi-tenant Rails application) is a different and much broader question.
More generally, be aware that anything that comes from a request can very easily be forged by a user. Always implement security server-side and do not trust user input!
Edit (seeing your code)
To prevent users updating others' Campings, you need to check in update after getting the #camping object (the second line) whether that's a camping object that your logged on user (current_user.id) is supposed to be able to edit.
The same way, if you want to prevent users from creating Campings for other users, you need to make sure in create that user_id will be set to the current user, something like #camping.user_id=current_user.id.
Similarly, if you want to prevent having a look at each other's Campings, you need to add checks to edit, show and pretty much all actions that return such objects.
There are gems like cancan and cancancan that may help with access control in Rails, they are worth a look!

Your Question is quite interesting but simple In the any HTML View Any one can change anything this will cause a security wise vulnerability as well.
To avoid these issues we need to authenticate it by two way You have to check the code by like It should be use by Controller not by view.
Suppose If you are creating any article of particular user
So To avoid it what you can do You can set the User ID in Session and make a Helper Method to find Current User always
So that you can find current user directly from controller and create article according to user
def Create
#article = current_user.articles.create(article_params)
end
This kind of Two way checking you can put up so that It will be safe.
To avoid the spend time on these work you can use gem directly like Devise

Related

Creating new object with has_and_belongs_to_many association

My rails project consists of three models: User, Groups and Transactions. Groups and Transactions are connected by a has_and_belongs_to_many relationship and both belong to User. I'm trying to implement a feature where you can add new transactions on a groups' show page that will automatically be associated with the show pages' group. I've tried the following but in the transactions controller rails doesn't get which group the transaction is supposed to be associated with.
Groups' show page:
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #group.name %>
<% #group.deals.each do |deal| %>
<%= deal.name %>
<%= deal.user.name %>
<%= link_to 'Show', deal %>
<% end %>
</p>
<%= link_to 'Edit', edit_group_path(#group) %> |
<%= link_to 'Back', groups_path %>
<%= link_to 'New Transaction', new_transaction_path(#group) %> |
Group's controller page:
# GET /transactions/new
def new
#transaction = Transaction.new
end
# POST /transactions or /transactions.json
def create
#transaction = Transaction.new(transaction_params.merge(user_id: current_user.id))
respond_to do |format|
if #transaction.save
format.html { redirect_to #transaction, notice: "Transaction was successfully created." }
format.json { render :show, status: :created, location: #transaction }
#transaction.groups << #group
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #transaction.errors, status: :unprocessable_entity }
end
end
end
If I replace #group with f.e. Group.first the association is created - it's the wrong one in most cases ofc tho. Does the solution lie within in the views maybe, can anyone help out?

Ruby on Rails - Create polymorphic comment through partial

I'm currently trying to implement polymorphic comments within my app, but I'm running into problems with converting my partial form.
I was following this tutorial, step-by-step-guide-to-polymorphic-associations-in-rails, but it didn't go over this section.
Mainly, I have an Image that is commentable, and a partial at the bottom to allow users to comment on the Image.
However, when submitting the form, it can't find the #commentable object as params[:id] and params[:image_id] are both nil.
I'm having problems understanding how I'm supposed to pass this information, as the partial knows this information, but the controller does not.
// images/show.html.erb
<div class="container comment-form" >
<%= render 'comments/form', comment: #image.comments.build %>
</div>
// comments/_form.html.erb
<%= bootstrap_form_for(comment) do |f| %>
<%= f.text_area :message, :hide_label => true, :placeholder => 'Add a comment' %>
<%= f.submit 'Reply', :class=> 'btn btn-default pull-right' %>
<% end %>
// comments_controller.rb
def create
#commentable = find_commentable
#comment = #commentable.comments.build(comment_params) <<<<<
respond_to do |format|
if #comment.save
format.html { redirect_to (comment_path #comment), notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: #comment }
else
format.html { render :new }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
Error on #comment = #commentable.comments.build(comment_params)
undefined methodcomments' for nil:NilClass`
I also noticed that there is no id in the request parameters.
Parameters:
{"utf8"=>"✓", "authenticity_token"=>"xxxxxx", "comment"=>{"message"=>"nice photo"}, "commit"=>"Reply"}
Thanks for your help.
When you pass a record to a form builder rails uses the polymorphic route helpers* to lookup the url for the action attribute.
To route to a nested resource you need to pass the parent and child(ren) in an array:
bootstrap_form_for([#commentable, #comment])
# or
bootstrap_form_for([#comment.commentable, #comment])
This would give the path /images/:image_id/comments for a new record and /images/:image_id/comments/:id if it has been persisted.
You are attempting to build your comment twice. Once in the show.html, with comment: #image.comments.build and then again in your create method with #comment = #commentable.comments.build(comment_params) <<<<<
The tutorial you linked to included the private method below. If your goal is to create a comment that belongs to your Image object, the method below would look for a param with your image_id, and would return Image.find(params[:image_id])
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
You could change your show.html to pass in your image_id as a hidden param with:
<div class="container comment-form" >
<%= render 'comments/form', image_id: #image.id %>
</div>

get value from form_for

I'm using rails 4.0.1
<%= form_for #event, :html => { :multipart => true} do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.label :place_id %><br>
<%= f.collection_select(:place_id, #places, :id, :title) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And I want to check for current_user.id and Place.user_id (it stores creator id). In Events cotroller i'm trying to use:
def create
#places = Place.all
#event = Event.new(event_params)
#event.user_id = current_user.id
#curplace = Place.find_by(id: params[:place_id])
#event.content = #curplace.id
respond_to do |format|
if #event.save
format.html { redirect_to #event, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: #event }
else
format.html { render action: 'new' }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
But i got an error. I think i'm not getting this Place_id param right or anything else?
Further to the comment from Ankush Kataria, the form_for helper basically creates a form which combines all the params into a hash, as opposed to form_tag, which just makes the params independently
As you've discovered, this means your params will be accessed by:
#form_for
params[:variable][:param]
#form_tag
params[:param]
form_for
The reason why this is important is because if you're using the RESTful routes interface, you'll be able to create / edit / update a variety of records
form_for basically keeps consistency throughout this process, pre-populating your forms with the various values, and keeping your code DRY
To call a form_for helper, you have to define the #varaible the form will populate. This #variable needs to be an ActiveRecord object, and is why you have to build it in the new action before your form shows
form_tag
form_tag is much more independent of the form_for helper, doesn't require any #variable, and creates the params individually
You'd use a form_tag for the likes of a contact us form or similar
Your Code
Your form looks good, but your create action can be dried up:
def create
#places = Place.all
#event = Event.new(event_params)
respond_to do |format|
if #event.save
format.html { redirect_to #event, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: #event }
else
format.html { render action: 'new' }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
end
end
private
def event_params
params.require(:event).permit(:title, :content).merge(user_id: current_user.id, place_id: params[:event][:place_id])
end
You are right that params[:place_id] isn't returning the value you expect. It only returns nil. To get the :place_id that's submitted by the form, you have to do this:
#curplace = Place.find(params[:event][:place_id])
Just replace the old line with the code above. It's because your form submits the data in the fields inside an :event key in the params hash since you're using the form_for helper method provided by Rails. That is its default behavior unless you change the 'name' attribute's value in the input fields.
Hope that helps!

Ruby on Rails: Submitting to table two different ways

I have an app where the user can submit a project. For each field they have a choice of either putting in new data into the database, or selecting old data from past projects to fill that field.
I am having trouble getting this to work for this piece of code in my New view:
<%= form_for(#technol) do |tech| %>
<%= fields_for(#project_technol) do |ab| %>
<%= text_field_tag :tech, nil, :maxlength => 30 %>
OR<br />
<%= ab.label "All Tech"%> </br>
<%= collection_select( :technols, :id, Technol.all, :id, :tech, {}, {:multiple => true } ) %>
</div>
<% end %>
<% end %>
At the moment the user can select many technologies from the collection_select, and they get saved with the project, but I am trying to give them the option to put there own technologies in through a text box.
My controller actions:
NEW
def new
#project = Project.new
#technol = Technol.new(params[:tech])
#all_technols = Technol.all
tech_ids = params[:technols][:id].reject(&:blank?) unless params[:technols].nil?
#project_technol = #project.projecttechnols.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: #project }
end
end
CREATE
def create
#project = Project.new(params[:project])
params[:technols][:id].each do |tech|
if !tech.empty?
#project.projecttechnols.build(:technol_id => tech)
end
end
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render json: #project, status: :created, location: #project }
else
format.html { render action: "new" }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
So to sum up, I want the user to have the option to enter new tech into the database, AND select existing tech from the dropdown, then all get saved with the project, and the new tech entered get saved in the technol table.
Any ideas? I am a rails noob so please remember this when trying to answer. Any help will be much appreciated. Thanks in advance
How about using token fields instead of a drop down and text field?
Check this revised RailsCast:
http://railscasts.com/episodes/258-token-fields-revised
Here's the original screen cast that's free if you don't have a RailsCast subscription:
http://railscasts.com/episodes/258-token-fields
I will suggest you to use a autocomplete which accepts multiple values. which will improve your view plus the coding will be easy

Ruby on Rails update model with more than one row in a single form

I have 2 models Event and Tasks.
Event has many tasks. and task is a nested resource under event
so I first create a event and ask a user how many tasks it wants to create in it.
Let say I create a Event and a user wants to create 3 tasks in it. I want to do it in 2 steps and not one
After successful creation of event,now I go to /events/1/tasks/new
here I want to have 3 task name fields and when the user submits it, there should be 3 rows created in Task table against the Event 1
How do I achieve this
So here is the task _form.html.erb
<%= form_for [#event, #task] do |f| %>
<% if #task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% #task.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Task controller
def new
#event=Event.find(params[:event_id])
#event.task_count do
#choice = #event.tasks.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: #task }
end
end
# POST /tasks
# POST /tasks.json
def create
#task = Task.new(params[:task])
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render json: #task, status: :created, location: #task }
else
format.html { render action: "new" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
I think you are making this more complicated by involving the tasks controller. Controllers direct actions in the web application. But by your description you seem to be wanting to have 3 tasks auto created when the event is created (if I'm understanding you correctly). Other than entering the initial names this doesn't really involve the user.
Have them submit the names and when the events controller creates the event it should create the tasks there.
If your nested resource is more complicated it is a job for nested forms. You might benefit from this screencast:
http://railscasts.com/episodes/196-nested-model-form-part-1
First you intilized 3 task aginst one eveent in this way
def new
#event=Event.find(params[:event_id])
3.times{#event.tasks.build}
respond_to do |format|
format.html # new.html.erb
format.json { render json: #task }
end
end
Then it will be surely create 3 task against 1 event.or you can help from ryan rails cast for nested forms also

Resources