Brock Tillotson
Brock Tillotson

Reputation: 119

Simple Rails Security Questions

So I am writing an app in Rails 5, and I am interested in the security issues of a simple feature I am trying to write. Users make Picks, which are secret from one another until a certain time. If I pass:

@picks = Pick.all

which contains everyones picks, to the view with the controller, and then filter what is displayed depending on who the user is on the view, would a user be able to access that @picks variable using nefarious methods? At first I thought yes, but now I am thinking that the user just gets the raw view sent with no @picks variable. Unless users can sneaky dev their own html views?

Disregard that it's probably a better idea to do the filtering in the controller anyway, I just want to see if you can expose variables if you give them in full to the view and then filter them there.

Upvotes: 1

Views: 205

Answers (2)

Tom Aranda
Tom Aranda

Reputation: 6036

Short Answer:

No, the client cannot access the @picks variable directly. Your view would have to display the value of @picks in the view in order for the browser to receive it.

Long Answer:

However, it would be good practice to limit the data assigned to @picks before it gets to the view. As your codebase grows and ages, and perhaps other developers start maintaining it, you may not remember that the @picks variable contains data that should not be displayed in the view.

Six months down the road, when the client wants to update the view based on new feature enhancement, you do not want to rely on the developer who is modifying the view to know that @picks contains sensitive data.

Make life easy on future developers (including you) by restricting the content of @picks to those records that the user is allowed to see at the time. Using the code suggested in the comments is a good idea:

@picks = current_user.picks

Or better yet, add a method to your model that contains the business logic for determining which picks are available to the user at a given time:

class User < ApplicationRecord
...
  def authorized_picks
    # code that returns the picks this user is allowed to see right now
  end
...
end

And then your controller code is:

@picks = current_user.authorized_picks

That way all of your business logic is in the model, where it belongs 90% of the time. This also allows you to keep your code DRY by having the authorization logic all in one place.

Keep your code simple and DRY and you will thank yourself down the road.

Upvotes: 3

Rahul Sharma
Rahul Sharma

Reputation: 1431

No, They won't be able to get the instance variable which we use in haml/erb files. They just get the raw html.

As Ruby on rails does server rendering, all instance variables will be used to prepare view at the server side.

Anyways filtering should be done on controller side as best practice.

Upvotes: 1

Related Questions