1

如果数据库中不存在他输入的电子邮件,我想注册一个新用户。我有一个带有以下代码的自定义会话控制器:

resource = warden.authenticate!(:scope => resource_name, :recall => :failure)

scope = Devise::Mapping.find_scope!(resource_or_scope)
resource ||= resource_or_scope
sign_in(scope, resource) unless warden.user(scope) == resource

如何指示 Devise 在“失败”方法中注册用户?

4

2 回答 2

0

我不断吸引用户尝试使用“注册”表单“登录”。它与设计选择有很大关系,但我真的很喜欢包罗万象的想法。

我只是找到了自己的解决方案。我不喜欢它,但它很简单(一旦我终于弄明白了)。我覆盖了stackoverflow 上RegistrationsController的详细信息。这是我在网站主页上的注册表,原因有几个,所以在那里做似乎很合适。

您需要创建app/controllers/registrations_controller.rb并将代码放在那里:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    # This is where the magic happens. We actually check the validity of the
    # username (an email in my case) and password manally.
    email = params[:user][:email]
    if user = User.find_by_email(email)
      if user.valid_password?(params[:user][:password])
        sign_in(user)
        redirect_to '/'
        return
      end
    end


    # Default devise stuff
    build_resource(sign_up_params)
    resource_saved = resource.save
    yield resource if block_given?
    if resource_saved
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_flashing_format?
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      @validatable = devise_mapping.validatable?
      if @validatable
        @minimum_password_length = resource_class.password_length.min
      end
      respond_with resource
    end
  end

  def update
    super
  end
end

需要确保配置路由以使用此控制器,如我在上面链接到的其他 SO 帖子中所述。

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

祝你好运!

于 2014-10-28T00:19:54.970 回答
0

您可以使用 Devise遵循仅电子邮件注册方法。扩展它,您可以将失败方法发布到您已设置为仅处理电子邮件的注册控制器注册。

更新:最简单的方法之一是覆盖响应,如此 所示。除了你的情况,你可能想要这样的东西:

 def respond
   if http_auth?
     http_auth
   else
     user = User.create(..user information) #Create the user (register them)
     sign_in(user) # Sign in the user just created
     redirect  # Redirect to whatever page you want
   end
 end

这样,您可以拥有一个电子邮件字段,并且当用户未通过身份验证(用户不存在,密码错误等)时,将创建用户。当然,对于您的情况,您可能希望在其中嵌套另一个if块以检查用户是否存在,这样您就不会仅仅因为密码错误等而尝试创建另一个用户。

希望这可以帮助!

于 2012-12-27T19:37:38.290 回答