【问题标题】:Updating a user creates a new hash of an empty password :(更新用户会创建一个空密码的新哈希 :(
【发布时间】:2010-04-21 14:29:14
【问题描述】:

我正在为 Rails 创建一个用户系统,然后登录、注册等……一切正常。惊人的!至少,我是这么认为的。我尝试更新用户的profile 属性,但我没有发送新密码或用户名。我在我的User 模型中使用它:

protected

def after_validation
  self.password = Password::update(self.password)
end

Password::update 方法对密码进行加盐和哈希处理以确保安全。问题是,只要我在保存时没有指定password,Rails 就会尝试保存一个空密码。我在我的UsersController 中使用它:

  # PUT /users/1
  # PUT /users/1.xml
  # PUT /users/1.json
  def update
    @user = current_user

    respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = 'User was successfully updated.'
        format.html { redirect_to(@user) }
        format.xml  { head :ok }
        format.json { head :ok }
      else
        @user.password = "[FILTERED]" # Hide for security
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
        format.json { render :json => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

但是,我的模型验证了空密码,但仍然保存了一个(n)(一个的盐渍哈希)空密码。但它应该只保存:profile 字段,如果这是唯一给定的字段(当然还有:updated_at 字段)。

所以我实际上的意思是当我更新记录而不指定当前密码时,密码属性仍然保存为空字符串的哈希。我希望update_attributes 如果未设置密码,则应忽略密码。

有人可以帮忙吗?谢谢

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我不完全确定我理解你的问题,但是如何添加:

    validates_presence_of :password
    
    def before_create
      self.password = Password::update(self.password)
    end
    

    【讨论】:

    • 对不起。我实际上的意思是,当我在不指定当前密码的情况下更新记录时,密码属性仍然保存为空字符串的哈希值。我的意思是 update_attributes 如果未设置,则应忽略 password
    【解决方案2】:

    我自己已经发现了。

    我必须检查密码是否已更改:

    def after_validation
      self.password = Password::update(self.password) if password_changed?
    end
    

    【讨论】:

      猜你喜欢
      • 2014-07-15
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2017-03-08
      相关资源
      最近更新 更多