Rails 2+: Sanitize SQL string
Indeed it is sometimes useful to sanitize a query to avoid (most of) SQL injections.
Typically, this is the case with your favorite text search field on a website.
Obvisouly, you can’t do better than using the Rails standard way of querying, who automatically applies this mechanism. For instance:
MyModel.find(:all,:conditions => ['name LIKE ?','%'+params[:search]+'%'])
But what if you want to create a fragment of a where clause?
This happens in few cases where you create complex queries in different parts of your code.
Well, if you’re in a ActiveRecord model, you can directly call
sanitize_sql_for_conditions(['name LIKE ?','%'+params[:search]+'%'])
to output a sql sanitized string.
Easy.
But if you’re in a controller or a custom library, you will surely fall on this
NoMethodError: protected method `sanitize_sql_for_conditions' called for ActiveRecord::Base:Class
Arrrgg!
Well, the answer is quite simple though. Just call the method right inside ActiveRecord:
ActiveRecord::Base.send(:sanitize_sql_for_conditions,['name LIKE ?','%'+params[:search]+'%'])
Hope it helps!
Facebook Connect and Rails: handling logout from Facebook site in Facebooker
Integrating an existing website with Facebook Connect using Facebooker is fairly easy. Several tutorial have been made; the best I found being:
However, there is no description on how to handle a frequent use case where the user has been authentified in your application using Facebook Connect and disconnects in the Facebook website.
In this case, you will surely meet the famous:
Facebooker::Session::SessionExpired (Session key invalid or no longer valid)
One solution to handle this is
rescue_from introduced in Rails 2.0. This is also the method recommended in the
Facebooker documentation.
When the exception occurs, you have to remove the facebook session informations AND facebooker cookies.
Indeed, the set_facebook_session will recreate the facebook_session with these cookies. If you do not remove them, you will loop again and again in your rescue_from handling.
Here is an example of what you can do:
class ApplicationController < ActionController::Base
...
rescue_from Facebooker::Session::SessionExpired do |exception|
clear_facebook_session_information
clear_fb_cookies!
reset_session # i.e. logout the user
flash[:notice] = "You have been disconnected from Facebook."
redirect_to root_url
end
...
end
Dead simple, huh?