1

My controller finds a user using:

@user = User.find_by_identifier!(params[:id])

In my Users model, i have

class User < ActiveRecord::Base

      def to_param
        identifier
      end

private 

  def create_identifier
    SecureRandom.urlsafe_base64(9)
  end
end

Question: Is this safe from an SQL injection point? And how so, since I have no clue about SQL injection despite reading various articles.

1 Answer 1

2

A quick experiment in my own console indicates that find_by_identifier! is safe against SQL injection.

irb(main):005:0> User.find_by_email! "i am sneaky '; drop table woot;"
  User Load (0.8ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'derp ''; drop table woot;' LIMIT 1

Notice how the generated SQL query escapes the malicious single-quote.

I believe that the to_param and create_identifier in your model are irrelevant.

Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense. I also have another sql query which uses a where conditional in the Users model. I use it in the index action to fetch users from the same city as the current_user: scope :same_city, lambda { |user| joins(:profile).where(:profiles => {:city => user.profile.city})} Would this be a threat? Sorry, I am a complete noob (despite all the points and badges I have racked up on this site)
This is explained in the Active Record Query Interface Guide

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.