22
votes

I am using devise gem for authentication.

In my application admin will create the users, so I want the user's reset password link when admin creates users.

This is my action:-

def create
   @user = User.new(user_params)
   @user.password = '123123123'
   @user.password_confirmation = '123123123'
   if @user.save
         @user.update_attributes(:confirmation_token => nil,:confirmed_at => Time.now,:reset_password_token => (0...16).map{(65+rand(26)).chr}.join,:reset_password_sent_at => Time.now)
       UserMailer.user_link(@user).deliver
       redirect_to users_path
     else
    render :action => "new"
   end
end

This is my link to reset a user's password

But I am getting reset password token is invalid when I open the link and update the password.

4

4 Answers

48
votes

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

18
votes

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_token
user.reset_password_sent_at = Time.now.utc

Then send them an email with the link:

edit_password_url(@user, reset_password_token: @token)
16
votes

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).

15
votes

You can use user.send_reset_password_instructions for that.