Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rack and rack.request.form_vars / rack.request.form_hash

I am doing some middleware that changes the authenticity_token param before it gets to Rails.

I can see that env.inspect gives both rack.request.form_vars and rack.request.form_hash. Both contains the authenticity token. Which one does Rails use and why does Rack provide both?

like image 389
jriff Avatar asked Feb 17 '11 12:02

jriff


2 Answers

Let's look at the source! The both variables come from using the Rack::Request helper class. It provides a nice interface to the request parameters. It's not necessary for Rack applications to use it, but Rails does use it.

The variables are for Rack::Request's internal use. rack.request.form_vars contains the unparsed POST body and rack.request.form_hash contains the parsed hash. ActionDispatch::Request inherits from Rack::Request and it gets the parameters using Rack::Request#POST, which reads the latter variable. You could use Rack::Request yourself to modify it.

class YourMiddleware
  def initialize(app)
    @app = app
  end 

  def call(env)
    req = Rack::Request.new(env)
    req.POST["authenticity_token"] = "foo"
  end
end
like image 77
Miikka Avatar answered Sep 30 '22 03:09

Miikka


If you have a recent copy of rack that includes this pull request, you can use Rack::Request#update_param:

request = Rack::Request.new(env)
request.update_param :auth_token, 'XXXXXXXXXXXXXXXX'

Just like the req.POST solution above, this will persist in the env that is passed among middlewares - but it's a higher-level call meant to deal with situations like yours.

like image 40
Seamus Abshere Avatar answered Sep 30 '22 03:09

Seamus Abshere