bekkou68 の日記

Gogengo! や IT 技術など。

Rails で warden.rb を編集後に redirect_to 後の flash に値が空になる - Value of flash After redirect_to Becomes Empty Caused by Editing warden.rb

サンプルソースコード - Sample Source Code

http://github.com/bekkou68/openid

現象 - Phenomenon

Rails で config/initializers/warden.rb を以下のように編集したら、redirect_to 後の flash に値が空になりました。 - The value of flash after redirect_to became empty when I edited config/initializers/warden.rb as follows on Rails.

require 'warden-openid'

Rails.configuration.middleware.use Rack::OpenID
Rails.configuration.middleware.use Rack::Session::Cookie
Rails.configuration.middleware.use RailsWarden::Manager do |manager|
  manager.default_strategies :openid
  manager.failure_app = SessionsController
end
...

原因 - Cause

デフォルトのセッション層のレイヤと warden.rb で設定した Rack のレイヤが衝突したため。 - The conflict of the default session layer and Rack layer set by warden.rb.

原因の検証 - Check for Cause

新規アプリケーションを作成してデフォルトのミドルウェアを表示します。 - Create a new application and display the default middleware.

$ rake middleware 
# (in /home/bekkou/sample)
# ...
# use ActionDispatch::Session::CookieStore
# ...

このように、デフォルトでセッション層にレイヤが存在します。(ちなみに、Sinatra ではそれは無いです) - As you see, the layer on session exists as default. (FYI, Sinatra has not.)

サンプルソースコードでも表示してみます。 - Now displays it on the sample source code.

$ rake middleware 
# (in /home/bekkou/openid)
# ...
# use ActionDispatch::Session::CookieStore
# ...
# use Rack::Session::Cookie
# ...

セッション層にレイヤが重複していますね。これらの衝突が原因です。 - The layers are duplicated on session layer. The conflict of them is cause.

対策 - Countermeasure

config/initializers/warden.rb の - Delete

Rails.configuration.middleware.use Rack::Session::Cookie

を削除。 - of config/initializers/warden.rb.

以下は編集後。 - The following is the post editing one.

require 'warden-openid'

Rails.configuration.middleware.use Rack::OpenID
Rails.configuration.middleware.use RailsWarden::Manager do |manager|
  manager.default_strategies :openid
  manager.failure_app = SessionsController
end
...

サーバを再起動し、ミドルウェアを確認。 - Reboot the server and confirm the middleware.

$ rake middleware 
# (in /home/bekkou/openid)
# ...
# use ActionDispatch::Session::CookieStore
# ...

よし! - OK!

また、redirect_to 後の flash にも値が入ってます! - And flash has value after redirect_to.

最後に

対策を教えてくれた @idesaku さん, 原因を教えてくれた @ursm さん, Twitter で Mention してくれた @a_matsuda さん, @tmaeda さんありがとうございました。 - Thanks @idesaku-san for telling the countermeasure, @ursm-san for teaching the cause, and @a_matsuda-san and @tmaeda-san for mentioning on Twitter.