开发者

Can my app be notified when a session is destroyed? If so, how?

My Devise/Warden-based app stores a model ID in the session[] variable. I want destroy the object when the session[] is destroyed.

  • Is there a callback or some mechanism to notify my app when the session is destroyed?
  • Is the mechanism dependable, or should I run a nightly cleanup script to vacuum up any orphaned objects?

To make it clear, here's a snippet of my controller code:

class WizardsContro开发者_如何学Cller < ApplicationController
  before_filter :find_or_create_wizard
  ...
private

  def find_or_create_wizard
    @wizard = Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
  end

end

To restate the question: how and when should I destroy the Wizard object?


Warden::Manager.before_logout do |user,auth,opts| 
  # callback 
end 

Use the Warden::Hooks https://github.com/hassox/warden/blob/master/lib/warden/hooks.rb to do things after sign out or authentication.


By session, do you mean when the user logs out?

Try monkey patching the sign_out method in your application_controller.rb You can find the relevant Gem code in lib/devise/controllers/helpers.rb

def sign_out(resource_or_scope=nil)
    Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
    super(resource_or_scope)
end

Session data is also cleared whenever a user signs in or signs up via a function called expire_session_data_after_sign_in!, could override that too:

def expire_session_data_after_sign_in!
        Wizard.find_by_id(session[:wizard_id]) || Wizard.create.tap {|w| session[:wizard_id] = w }
        super
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜