【问题标题】:Rails/Devise: not able to send confirmation mail manually from controllerRails/Devise:无法从控制器手动发送确认邮件
【发布时间】:2015-07-03 09:25:11
【问题描述】:

在我的 Rails/Devise 应用程序中,我需要为具有特定角色的用户手动发送确认电子邮件并延迟其发送。

我现在要做的是: a) 在 User.rb 中:

before_save :skip_mail_if_role1
def skip_mail_if_role1
  self.skip_confirmation_notification! if self.role == 'role1'
end

b) 在此角色用户的自定义注册控制器中:

Devise::Mailer.confirmation_instructions(resource, resource.confirmation_token).deliver_later(wait: 5.minutes)

当然,我收到一封带有错误令牌的电子邮件,并且单击按钮什么也没做。任何虚拟令牌也不做任何事情。当我没有传递第二个参数时,我得到参数错误(至少应该有 2 个参数,这很奇怪,就here 他们只传递 user 参数)。

所以我想知道我要从控制器那里传递什么作为令牌来完成这项工作?

更新:

使用this 指令我实现了自定义设计MyMailer,但我仍然不知道在调用MyMailer.confirmation_instructions(resource, ????).deliver 时应该在控制器中传递什么token 属性

【问题讨论】:

  • 使用 user.reload 获取最新生成的令牌
  • @Milind user.reload 不会更改令牌 - 它仍然相同并且仍然错误

标签: ruby-on-rails email devise token devise-confirmable


【解决方案1】:

我覆盖了devise 的默认逻辑来生成令牌,然后用它来确认和发送电子邮件...

user.rb

  def create_password_reset_token
    Rails.logger.info "=======Creating reset password token======="
    generate_token(:reset_password_token) ##unless self.reset_password_token.present?
    update_attribute(:reset_password_sent_at,Time.zone.now)
    save!
    ####refresh the user to get latest token which is used to reset password as find_by_reset_password_token
    self.reload
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end  ##while User.exists?(column => self[column])
  end

并在您自己的发送电子邮件的方法中使用上述逻辑

 def send_reset_password_instructions(attributes={})
        user=User.find_by_email attributes['email']
        ##generate reset password token shown above
        user.create_password_reset_token 
        ##@resource=User.find_by_email(attributes['email'])
        #i used delay,you may use delay_for() or delay_until as needed from sidekiq
        UserMailer.reset_password_instructions(attributes['email']).deliver

      end

【讨论】:

  • 我重新实现了它直到确认邮件,但它仍然没有确认用户。我要做的是:1)把上面的方法create_confirmation_token逻辑放到我的user.rb; 2) 在super 之前将user.create_confirmation_token 添加到我的自定义CustomDeviseMailer < Devise::Mailer 邮件方法def confirmation_instructions(user, token, opts={})。它什么也没做,我仍然得到从控制台获得的令牌,并且链接仍然没有确认
  • 不要使用 super...否则它将再次退回到默认实现...当您覆盖默认行为时...您不需要使用 super...@Vla跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2011-08-20
  • 2019-11-29
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多