1

I'm trying to figure out how I can check if a user reset token is valid BEFORE loading the reset password form. The issue is, currently users don't find out until after they submit.

Here is what I have

class PasswordsController < Devise::PasswordsController
before_action :check_valid_token

private

def check_valid_token
  resetCode = (params['resetCode'])
  reset_password_token = Devise.token_generator.digest(self, :reset_password_by_token, resetCode)
  user = User.find_by(reset_password_token: @reset_password_token)
  if user == nil
    redirect_to root_path
  end
end
end

This doesn't work and I can't find much documentation.

  • Don't try this `User.find_by(reset_password_token: @reset_password_token)` looks risky. Let the user pass in his email and use that to find the record. The do `if params['resetCode'] == User.reset_password_token'`. – Beulah Akindele Mar 31 '20 at 19:55
  • Hey, I changed it to that and then I got this undefined method `reset_password_token' for # I'm sure I'm missing something and just new to this. Rails can't figure out what User.reset_password_token is. – Barrett Shepherd Mar 31 '20 at 22:29
  • Could it be that instead of passing `self` (which is an object of `PasswordsController`) you have to pass in `User` ? Thus: `Digest.token_generator.digest(User, ...)` – lxxxvi Jul 23 '20 at 08:34

2 Answers2

4

Devise reset password token will be stored as hashed value. You need to decode it.

  def check_valid_token
    token = Devise.token_generator.digest(User, :reset_password_token, params['reset_password_token'])
    user = User.find_by(reset_password_token: token)
    user.present?
  end

This method will return, true or false

Jin Lim
  • 1,759
  • 20
  • 24
0

I would do something basic, like this:

def check_valid_token
  @user = User.find_by!(reset_password_token: params[:token])
rescue ActiveRecord::RecordNotFound
  redirect_to root_path
end

so you will have @user instance if token fits and if not it will redirect user to the root_path. You can also add some message before redirecting, like
flash.now[:error] = "Some message here"

Roman Alekseiev
  • 1,854
  • 16
  • 24