0

我正在尝试使用 gem bcrypt 和 hash-salt 方法更改用户密码。

这是我的代码,其中包含我更改密码的尝试,但它给了我一个缺少模板的错误。

用户控制器

def create

    @user = User.new(user_params)

end

def change_password
    @user = User.find(params[:id])
    if @user.password_hash == BCrypt::Engine.hash_secret(params[:current_password], @user.password_salt)
      @user.password = params[:password]
      @user.save
      redirect_to "/users/#{@user.id}"
    end
end
private

def user_params
  params.require(:user).permit(:email, :password, :password_confirmation)
end

用户模型

before_save :encrypt_password


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


def encrypt_password
    if password.present?
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
end

还有,路线

patch 'users/:id/change_password' => 'users#change_password'
resources :users

最后但同样重要的是形式

<%= 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 :contraseña_actual %></div>
    <div class="form-group col-md-8"><%= f.password_field(:current_password, :class => "form-control") %></div>
  </div>

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

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

  <div class="col-md-offset-2 col-md-10">
    <button type="submit" class="btn btn-default">Cambiar Contraseña</button>
  </div>
<% end %>
4

0 回答 0