Cross Site Scripting Be Gone! (with sessions)

Cross Site Scripting is nasty stuff. Mean guy puts this in his website and tells you to go look:

<img src="http://yourdomain.com/camping/best-app-evar/delete-all-my-stuff"/>

Oh no! All your stuff is mysteriously missing! That sure would be bad. Here's how you can fix it in your app which uses CampingSessions or CookieSessions.

module Camping::Helpers
  # the following two methods are used to sign url's so XSS attacks are stopped dead
  # it works because XSS attackers can't read the data in our session.
  def sign
    @state.request_signature ||= rand(39_000).to_s(16)
  end
  
  def signed?
    input.signed == @state.request_signature
  end
end

Now in your view, when you make a link, do it like this!

a("Delete All My Stuff", :href => R(DeleteAllMyStuff, :signed => sign))

And finally, over in your controllers...

class DeleteAllMyStuff < R('/delete-all-my-stuff')
  def get
    return unless signed?
    stuff.delete!
    "It's all gone, sorry dude!"
  end
end

And your problems will be solved! Now Fred next door can't guess the right url to put in that image on his MySpace page to delete all your stuff because there is an important random number in there! Yay! Sorry Fred, better luck next time! Now lets go Camping!