簡體   English   中英

使用bcrypt進行身份驗證以更改密碼

[英]Authenticate with bcrypt for change password

好吧,在更改用戶密碼時,我在對用戶進行身份驗證時遇到問題,我收到了郵件和密碼並運行了self.authenticate ,但是它self.authenticate返回nil

我使用與登錄時相同的格式。這是代碼

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_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 %>

我只是想弄清楚為什么它總是返回nil以及如何成功更改密碼。

我終於找到了所有問題的原因

  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

有解決的方法,我必須直接指定參數,僅此而已

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM