4
votes

controller

def create
 # admin manually creates user
 UserMailer.reset_password_instructions(@user).deliver
end

user.rb

class User < ActiveRecord::Base

  before_create :generate_reset_password_token # generating devise reset token

  # Include default devise modules. Others available are:
  # :confirmable, :lockable and :omniauthable
  # :registerable,
  # :trackable,
  devise  :database_authenticatable,
          # :confirmable,
          :rememberable,
          :validatable,
          :recoverable,
          :trackable,
          :timeoutable


private

  # Generates a new random token for confirmation, and stores
  # the time this token is being generated
  def generate_reset_password_token
    raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)
    @raw_confirmation_token   = raw
    self.reset_password_token   = enc
    self.reset_password_sent_at = Time.now.utc
  end

end

user_mailer.rb

class UserMailer < ApplicationMailer
  include Devise::Mailers::Helpers

   default from: '[email protected]'

   def reset_password_instructions(resource, opts={})
    @resource = resource
    @token    = @resource.reset_password_token
    mail(to: @resource.email, subject: "Reset Password Instructions")
   end
end

reset_password_instructions.html.erb

<p>Hello <%= @resource.email %>!</p>

<p>Someone has requested a link to change your password. You can do this through the link below.</p>

<p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %></p>

<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>

At this point, when user is created manually by admin, Password reset Link is going to the email address, which I can see using MailCatcher or letter_opener. http://lvh.me:3000/users/password/edit?reset_password_token=6a8bc4683fc9e5dfcc789f94f9b6bd2b1c44fd857f13662d0f0d1f6212022f81

I click on the link and it successfully took me to edit password page. When I submit form, ivalidation failed with Reset password token is invalid message.

What am I missing here....

UPDATE:

My Development.rb looks like:

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports and disable caching.
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # Adds additional error checking when serving assets at runtime.
  # Checks for improperly declared sprockets dependencies.
  # Raises helpful error messages.
  config.assets.raise_runtime_errors = true

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Configure letter opener to open email in browser
  # config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = { :address => "lvh.me", :port => 1025 }
  config.action_mailer.default_url_options = { host: 'lvh.me', port: 3000 }

  config.domain = 'lvh.me'
end
2
What does your development.rb looks like? - Sylar
Remove config.domain and add config.action_mailer.default_url_options = { :host => 'localhost:3000' } See what happens. Restart server first. - Sylar
Nope, that didn't solved my problem. config.domain is just a config variable I am using to set session in session_store, something like: domain: Rails.configuration.domain. - przbadu
Whats your devise version? - Sylar
Have a read on this as somewhere in your user.rb doesnt look right: github.com/plataformatec/devise/blob/v3.5.1/lib/devise/models/… - Sylar

2 Answers

3
votes

There was a one line code for my solution, which I have made complicated by adding manual mailer, actions, etc.

To solve this problem I just have to call devise's send_reset_password_instructions in user object:

In controller

    @user.send_reset_password_instructions

Solved my problem.

I cleaned up my code by removing (as per my question:)

  • user_mailer.rb file is no more required, so deleted it

  • views/user_mailer/reset_password_instructions.html.erb file is not required, so deleted it.

  • In User.rb model, remove before_action :generate_reset_password_token as well as generate_reset_password_token private method.

  • Remove below mailer line from controller

    UserMailer.reset_password_instructions(@user).deliver

3
votes

I went crazy deep with this, and finally found the answer:

  def generate_reset_password_token
    raw, enc = Devise.token_generator.generate(self.class, :reset_password_token)
    @raw_confirmation_token   = raw
    self.reset_password_token   = enc
    self.reset_password_sent_at = Time.now.utc
  end

This code is right, you want the user to have enc as the reset_password_token. It's also good that you keep the raw variable handy.

class UserMailer < ApplicationMailer
  include Devise::Mailers::Helpers

   default from: '[email protected]'

   def reset_password_instructions(resource, opts={})
    @resource = resource
    @token    = @resource.reset_password_token
    mail(to: @resource.email, subject: "Reset Password Instructions")
   end
end

For this part, you want @token = @raw_confirmation_token (raw from the token generator), not @resource.reset_password_token (which is enc from the generator).

I believe this solution is for devise 3.1+, it seems they changed their setup for added security, without explaining the two tokens.