How to generate reset password token How to generate reset password token ruby-on-rails ruby-on-rails

How to generate reset password token


If you are using devise why are you creating your own password reset token?Devise has a feature for that.http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable

In case you wonder this is what devise does when the user wants to reset his password:

  raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)  self.reset_password_token   = enc  self.reset_password_sent_at = Time.now.utc  self.save(validate: false)

self is an User object here

In your URL you then have to pass raw as reset_password_token parameter


You can generate a token with:

Devise.token_generator.generate(User, :reset_password_token)

Though this is just a useless string by itself. You need to attach it to the user if you actually want to use it in a link to reset passwords:

user.reset_password_token = hashed_tokenuser.reset_password_sent_at = Time.now.utc

Then send them an email with the link:

edit_password_url(@user, reset_password_token: @token)


If you don't want it to send the instructions, just set and store the token you can call the private method in devise recoverable concern set_reset_password_token.

You can do this by doing something like user.send(:set_reset_password_token).