如何在 Rails 中设计电子邮件确认后登录用户

joh*_*ohn 2 ruby authentication ruby-on-rails devise

我在过去 7 小时内尝试在电子邮件确认后自动登录用户,但当我单击确认链接时,它会显示“您的电子邮件地址已成功确认”。但不登录用户。我已经在我的确认控制器和路由中编写了这段代码

devise_for :users, controllers: {confirmations: 'users/confirmations'}

class ConfirmationsController < Devise::ConfirmationsController
  #private
  def after_confirmation_path_for(resource_name, resource)
    sign_in(resource)
    render plain: "here"
    redirect_to "/admins/view_account", notice: "User deleted."
  end
end
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激谢谢。

fag*_*ani 5

请注意,电子邮件确认后自动登录曾经是 Devise 的默认行为,后来3.1由于安全措施而发生了更改(之后),您可以在此处此处查看更多信息。

如果您仍然想这样做,请根据 Devise 的版本,确保在config/initializers/devise.rb项目中的文件上设置以下行:

config.allow_insecure_sign_in_after_confirmation=true
Run Code Online (Sandbox Code Playgroud)

如果您使用的是最新的 Devise 版本,您可能必须使用此代码扩展默认控制器,app/controllers/users/confirmations_controller.rb以替换上面提到的控制器代码(请注意提到的命名空间和路径):

class Users::ConfirmationsController < Devise::ConfirmationsController
  def show
    super do |resource|
      sign_in(resource) if resource.errors.empty?
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

并确保您粘贴在问题开头的代码属于config/routes.rb

devise_for :users, controllers: { confirmations: 'users/confirmations' }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!