Send Password Reset to a Different Email - Devise

2019-02-25 15:13发布

问题:

I'm using ruby on rails 5 with devise and I need to send a password reset email to a different email than the one stored in my User table. How can this be achieved?

回答1:

Please note: it is pretty unrecommended way to implement things.
It is not within scope of the best practices.
It is dirty and fragile.
But if you really need to achieve it no matter how dirty are the measures, this is it.

Well, the requirement to send the reset instruction to other email is already weird enough. Is it really a last resort?

Anyway,

You've not specified the Devise version but that behaviour was unlikely changed too much so lets take the current master and look how it sends emails:

https://github.com/plataformatec/devise/blob/f39c6fd92774cb66f96f546d8d5e8281542b4e78/lib/devise/mailers/helpers.rb#L31

def headers_for(action, opts)
    headers = {
      subject: subject_for(action),
      to: resource.email,

So, the getter is somewhat hardcoded.

Though, it is possible to create a token and set it as Devise does:

https://github.com/plataformatec/devise/blob/d1948b79d3e933253baa753bd033c92171c0a7d0/lib/devise/models/recoverable.rb#L89

def set_reset_password_token
  raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)

  self.reset_password_token   = enc
  self.reset_password_sent_at = Time.now.utc
  save(validate: false)
  raw
end

And when find in sources how Devise sends it and try to somehow replicate it but using your custom email.

I think the less evil in this case would be just implementing your own mailer for that kind of reset instructions which would use the same URL as Devise does.
Otherwise you would have too much coupling with a current version of Devise.