Authenticate with bcrypt for change password

Well, I got a problem to authenticate the user at the moment of changing his/her password, I get the mail and password and run the self.authenticate, but it keep returning me nil

I use the same format as when I log in. Here's the code

user_controller.rb

def change_pw
    @user = User.authenticate(current_user.email, params[:password])
    logger.info current_user.email
    if @user.nil?

      logger.info params[:password]
      flash[:notice] = "incorrect password"
      redirect_to :back
    else
      if @user.valid?
        @user.password = @user.new_password unless @user.new_password.nil? || @user.new_password.empty?
        @user.save
        flash[:notice] = "Los cambios se han realizado exitosamente."
        redirect_to @user
      end  
    end   
end

user.rb

def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
        return user
    else
        return nil
    end
end

form

<%= form_for(@user, :url => "/change_password") do |f| %>

  <%= hidden_field(:user, :email, :value => @user.email) %>

  <div class="form-group">
    <div class="form-group col-md-4"><%= f.label :password %></div>
    <div class="form-group col-md-8"><%= f.password_field(:password, :class => "form-control") %></div>
  </div>

    <div class="form-group col-md-4"><%= f.label :new_password %></div>
    <div class="form-group col-md-8"><%= f.password_field(:new_password, :class => "form-control") %></div>

  <div class="form-group">
    <div class="form-group col-md-4"><%= f.label :new_password_confirmation %></div>
    <div class="form-group col-md-8"><%= f.password_field(:new_password_confirmation, :class => "form-control") %></div>    
  </div>

  <div class="col-md-offset-2 col-md-10">
    <button type="submit" class="btn btn-default">Change Password</button>
  </div>
<% end %>

I'm just trying to figure it out why it keeps returning me nil and how I can success on change password.

Upvotes: 0

Views: 1354

Answers (1)

I finally found the reason of all my problems

  def change_pw
    @user = User.authenticate(current_user.email, params[:user][:password])
    if @user.nil?
      flash[:notice] = "Contraseña incorrecta"
      redirect_to :back
    else
      if @user.valid?
        @user.password = params[:user][:new_password] unless params[:user][:new_password].nil? || params[:user][:new_password].empty?
        @user.save
        redirect_to @user
      end  
    end
  end

There's the way to solve it, i had to specified the params directly and that's all

Upvotes: 0

Related Questions