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

I am doing some middleware that modifies the authenticity_token parameter before it gets into Rails.

I see that env.inspect provides both rack.request.form_vars and rack.request.form_hash. Both contain an authentication token. Which one uses Rails and why does Rack provide both?

+4
source share
2 answers

Let's look at the source! Both variables come from the helper class Rack::Request . It provides a good interface for query parameters. Rack applications do not need to use Rails, but Rails uses it.

Variables for internal use Rack::Request . rack.request.form_vars contains the rack.request.form_vars POST body and rack.request.form_hash contains the parsed hash. ActionDispatch::Request inherits from Rack::Request and receives parameters using Rack::Request#POST , which reads the last variable. You can use Rack::Request yourself to change it.

 class YourMiddleware def initialize(app) @app = app end def call(env) req = Rack::Request.new(env) req.POST["authenticity_token"] = "foo" end end 
+7
source

If you have the latest copy of the rack that includes this Rack::Request#update_param request , you can use Rack::Request#update_param :

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

Like the previous req.POST solution, this will be stored in env , which is passed among intermediaries, but this is a higher level call designed to solve situations like yours.

+3
source

Source: https://habr.com/ru/post/1340169/


All Articles