Signing in existing users from Devise registrations

时间:2015-05-12 23:16:18

标签: ruby-on-rails devise

I'm toying with the idea of automatically signing a user in when they try to signup with existing, valid credentials.

So far, I tweaked .map():

Devise::RegistrationsController#create

This works fine in my test case but I was wondering if the approach was safe enough.

Perhaps other people have already tried something similar? Perhaps solutions already exist somewhere (this problem is so difficult to Google for)?

Also: are there potential downside with different authentication strategies? I only tried with def create_method_from_devise_controller existing_user = User.find_by_email(sign_up_params[:email]) if existing_user && existing_user.valid_password?(sign_up_params["password"]) && sign_in(:user, existing_user) respond_with existing_user, location: after_sign_in_path_for(existing_user) else super end end and rememberable.

1 个答案:

答案 0 :(得分:1)

更好的方法是使用Warden来验证用户,就像Devise::SessionsController一样。摘录来源:

  # POST /resource/sign_in
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_flashing_format?
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end

auth_options返回哈希:

{ scope: resource_name, recall: "#{controller_path}#new" }

这样您就不会复制实际的身份验证逻辑。如果您使用的是confirmable

,这会产生影响的实际情况
existing_user && existing_user.valid_password?(sign_up_params["password"]) && sign_in(:user, existing_user)

在您的示例中,重复的身份验证步骤仅考虑密码 - 这将作为允许未经证实的用户访问的后门。