发送确认后如何登录用户?

时间:2012-08-18 10:16:56

标签: ruby-on-rails devise override devise-confirmable

我使用设计来验证我的网站上的用户使用设计确认选项。现在,当用户注册时,他们会收到确认电子邮件,但我需要用户在发送确认后自动登录。

我希望用户即使不确认他们的电子邮件地址也能登录。

我知道我需要修改确认控制器,但不知道是什么以及如何。这是我的代码:

class Devise::ConfirmationsController < DeviseController
# GET /resource/confirmation/new
def new
 build_resource({})
end

# POST /resource/confirmation
def create
 self.resource = resource_class.send_confirmation_instructions(resource_params)
if successfully_sent?(resource)
  respond_with({}, :location => 
after_resending_confirmation_instructions_path_for(resource_name))
else
  respond_with(resource)
 end
end

 # GET /resource/confirmation?confirmation_token=abcdef
def show
 self.resource = resource_class.confirm_by_token(params[:confirmation_token])

if resource.errors.empty?
  set_flash_message(:notice, :confirmed) if is_navigational_format?
  sign_in(resource_name, resource)
   respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) }
 else
  respond_with_navigational(resource.errors, :status => :unprocessable_entity){ render :new }
 end
end

protected

# The path used after resending confirmation instructions.
def after_resending_confirmation_instructions_path_for(resource_name)
  new_session_path(resource_name)
end

# The path used after confirmation.
def after_confirmation_path_for(resource_name, resource)
  after_sign_in_path_for(resource)
end

 end

1 个答案:

答案 0 :(得分:2)

如果您查看第87行的设计初始化程序,您应该看到:

# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days

启用此功能后,您的用户可以登录一段时间,而无需通过确认电子邮件确认其帐户。如果您想在发送确认电子邮件后自动为用户签名,则需要覆盖设计confirmations_controller中的create方法。有关于如何覆盖Devise控制器的教程,但您需要执行以下操作:

def create
  self.resource = resource_class.send_confirmation_instructions(resource_params)

  if successfully_sent?(resource)
    sign_in(resource_name, resource)
    respond_with({}, :location => after_sign_up_path_for(resource)
  else
    respond_with(resource)
  end
end

这基本上是默认的Devise方法,使用额外的行来登录用户并通过调用respond_With更改after_sign_up_path_for。请注意,after_sign_up_path_for默认为根路由,这可能是不合需要的。 Devise Wiki上有一些关于覆盖这条道路的例子。