简体   繁体   English

Rails + Devise:如何在登录时检查是否记住了用户

[英]Rails + Devise: How can I check if a user is remembered when signing in

How can I find out if a user who is signing in was remembered through an older session. 我如何确定登录的用户是否在较旧的会话中被记住。

I found this answer: Rails/Devise: execute action after automatic login and it says that the after_remembered method gets called after a user was remembered. 我找到了这个答案: Rails / Devise:自动登录后执行操作 ,它说在记住用户后调用after_remembered方法。 I tried it out and put it in my model but it doesn't get called. 我尝试了一下,然后将其放入模型中,但是没有被调用。 I even put a binding.pry before this line https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb#L30 but the whole authenticate! 我什至在此行之前放置了binding.pry https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb#L30,但整个过程都进行了身份验证! method doesn't even get called when signing in. 登录时甚至不会调用方法。

I hope someone can help 我希望有人能帮帮忙

Okay, my previous idea with creating an after_update callback didn't work since it wouldn't get updated on an remembered session. 好的,我以前创建after_update回调的想法不起作用,因为它不会在记住的会话中进行更新。

What I ended up doing isn't really pretty, but I also didn't want to monkeypatch warden. 我最终做的不是很漂亮,但是我也不想胡闹看守人。

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

For email only sign ins this is enough. 对于仅电子邮件登录,就足够了。 If you are using omniauth sign ins then you have to block every omniauth sign in in the check_remembered function by checking if params[:user][:email] is present. 如果使用的是omniauth登录,则必须通过检查是否存在params[:user][:email]来阻止check_remembered函数中的每个omniauth登录。 Those will have to be handled in your omniauth controller. 这些将必须在您的omniauth控制器中进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM