2015-11-12 19 views
2

如何才能確定登錄的用戶是否通過舊會話記住。Rails + Devise:如何檢查用戶是否在登錄時被記住

我找到了這個答案:Rails/Devise: execute action after automatic login 它說after_remembered方法在用戶被記住後被調用。我試了一下,並把它放在我的模型中,但它沒有被調用。 我甚至在此行之前放了一個binding.pry https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb#L30 但是整個驗證!方法不會在登錄時甚至調用。

我希望有人能幫助

+0

有一個名爲user_sign_in_count的設計附帶的列。你可以在after_sign_in方法中使用該方法,條件爲 – Ezequiel

+0

我發現的唯一一種類似於你提到的方法是https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb# L217,我認爲這不會對我有所幫助,因爲我必須檢查sign_in_count上的更改。如果用戶被記住,則計數不會改變。我的意思是我可以在控制器操作之前保存計數,並在完成後比較計數,但這真的很難。我希望有一個更優雅的解決方案。 – Mexxer

+0

當你說用戶時,你說的是已經註冊的用戶? – Ezequiel

回答

0

好吧,我以前的想法與創建after_update回調沒有工作,因爲它不會得到上記住會話更新。

我最終做的並不是很漂亮,但我也不想monkeypatch監獄長。

class Users::SessionsController < Devise::SessionsController 
    around_action :check_remembered, only: :create 

    def create 
    super 
    end 

    private 
    def check_remembered 
    # find the user based on the email in the login params. 
    # You can't use current_user here because once you call it, 
    # it will update the user before the action even ran (no idea why) 
    user = User.find_by_email(params[:user][:email]) 
    yield 
    if user && user.sign_in_count != current_user.sign_in_count 
     # user was not remembered 
    end 
    end 
end 

對於電子郵件只簽署這就夠了。如果您使用的是omniauth登錄,則必須通過檢查params[:user][:email]是否存在來阻止check_remembered函數中的每個omniauth登錄。那些將不得不在你的omniauth控制器中處理。