Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting Devise Password without an Email - Rails

So I have an app in which the users login with their cell phone numbers and get notifications via text/sms. It's a mobile app. I send texts via the applicationmailer by sending emails to "[email protected]" etc.

However, I have hit a wall with how to override the password reset instructions. I want the message to be sent via text (i don't have their email address), but how do I override devise to do this? I can have the user enter in their number and then do a lookup (i store the contact path as a field in the user, I generate the string in the backend, they don't have to do it).

Ideas?

thanks a bunch!

like image 995
Jason van der Merwe Avatar asked Nov 12 '22 05:11

Jason van der Merwe


1 Answers

You can do this by changing your

passwords_controller:

  def create
    assign_resource
    if @resource
      @resource.send_reset_password_instructions_email_sms
      errors = @resource.errors
      errors.empty? ? head(:no_content) : render_create_error(errors)
    else
      head(:not_found)
    end
  end

  private

  def assign_resource
    @email = resource_params[:email]
    phone_number = resource_params[:phone_number]
    if @email
      @resource = find_resource(:email, @email)
    elsif phone_number
      @resource = find_resource(:phone_number, phone_number)
    end
  end

  def find_resource(field, value)
    # overrides devise. To allow reset with other fields
    resource_class.where(field => value).first
  end

  def resource_params
    params.permit(:email, :phone_number)
  end

and then including this new concern in the users model

module Concerns
  module RecoverableCustomized
    extend ActiveSupport::Concern

    def send_reset_password_instructions_email_sms
      raw_token = set_reset_password_token
      send_reset_password_instructions_by_email(raw_token) if email
      send_reset_password_instructions_by_sms(raw_token) if phone_number
    end

    private

    def send_reset_password_instructions_by_email(raw_token)
      send_reset_password_instructions_notification(raw_token)
    end

    def send_reset_password_instructions_by_sms(raw_token)
      TexterResetPasswordJob.perform_later(id, raw_token)
    end
  end
end

which basically uses the private methods that the devise method sent_reset_password_instructions uses adding your own texting logic.

like image 119
Leti Esperón Avatar answered Nov 27 '22 18:11

Leti Esperón