DEV Community

loading...

Devise gem force confirmation on email change and remove old email

Zia Ul Rehman
Originally published at ziatechblog.wordpress.com on ・1 min read

Default behavior of devise when confirmable in model and reconfirmable in devise.rb are enabled is that it does send a reconfirmation email email if email is changed, but it does not remove/replace previous email and does allow users to still login through old email while new email’s confirmation is pending.

I am on rails 6.0.2, Devise 4.7.1 for the record.

Problem?

This is a bit odd behavior for some scenarios, like when users are being controlled by admins(lets say in tenants), sometimes we want to enforce email change and reconfirmation when admin changes the email of any user. I could not find any official solution for this issue, and i had to go with monkey patching.

Solution:

For this, i had to overwrite a method in my user model:

  # overwirte from /devise/models/confirmable.rb to force email re-confirmation for email changes
  def postpone_email_change_until_confirmation_and_regenerate_confirmation_token
    @reconfirmation_required = true
    self.unconfirmed_email = email
    # self.email = self.email_was
    self.confirmed_at = nil
    self.confirmation_token = nil
    generate_confirmation_token
  end

And voila, this replaces old email completely and forces a confirmation of that new email before users can continue using the system.

It took me a couple of hours to come to this solution after finding no official solution for this seemingly simple usecase, so logging for my record as well as for community. Happy coding!

Discussion (0)