0
votes

When trying to set a password for users without one (users already exist before devise was installed), devise returns a token errors.

controller action:

  if @user.password.nil? 
    raw, hashed_token = Devise.token_generator.generate(User, :reset_password_token)
    @user.reset_token = raw
    @user.reset_password_sent_at = Time.now.utc
    @user.save(validate: false)
    @tok = raw

    render :create_password, reset_password_token: raw

in the form I have the following:

<%= form_for(@user, as: :user, url: password_path(@user), html: { method: :put }) do |f| %>

  <!--devise_error_messages! -->

  <%= f.hidden_field :reset_password_token, value: @tok %>

  <div class="field">
    <%= f.label :password, "New password" %><br />
    <% if @minimum_password_length %>
      <em>(<%= @minimum_password_length %> characters minimum)</em><br />
    <% end %>
    <%= f.password_field :password, autofocus: true, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation, "Confirm new password" %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Change my password" %>
  </div>
<% end %>

When the user submits the form I receive an invalid token error.

My routes are setup like this

  devise_for :users, controllers: 
              {
                sessions: 'users/sessions',
                registrations: 'users/registrations'
              }

Is this the correct way to creating a password for existing users with no password?

1

1 Answers

0
votes

I suggest doing migration for updating password first cause "users already exist before devise was installed". In rails console, try:

user.update(password:"newpass", password_confirmation:"newpass")

You can create rake task to do it for a ton of User. Then using form to update would be fine.