Can I execute custom actions after successful sign in with Devise?

前端 未结 5 2331
春和景丽
春和景丽 2020-12-08 15:01

I have an app that has basic Devise authentication. After sign in, I would like to look up the user account (user belongs_to account, account has_many users), and store tha

5条回答
  •  一生所求
    2020-12-08 15:35

    Actually, the accepted answer does not work properly in case of combined Omniauth and Database login modules in Devise.

    The native hook that is executed after every successfull sign in action in Devise (disregarding the user authentication channel) is warden.set_user (called by devise sign_in helper: http://www.rubydoc.info/github/plataformatec/devise/Devise/Controllers/SignInOut#sign_in-instance_method).

    In order to execute custom action after successfull user sign in (according to Warden Docs: https://github.com/hassox/warden/wiki/Callbacks), put this into initializer (eg. after_sign_in.rb in config/initializers)

    Warden::Manager.after_set_user except: :fetch do |user, auth, opts|
      #your custom code
    end
    

    Update 2015-04-30: Thanks to @seanlinsley suggestion (see comments below), I have corrected the answer to include except: :fetch in order to trigger the callback only when user is authenticated and not every time it is set.

    Update 2018-12-27 Thanks to @thesecretmaster for pointing out that Warden now has built-in callbacks for executing your own code on after_authentication https://github.com/wardencommunity/warden/wiki/Callbacks#after_authentication

提交回复
热议问题