开发者

Updating a user creates a new hash of an empty password :(

I'm creating a user system for Rails, and login, sign up etc... all works. Awesome! At least, that is what I thought. I tried to update the profile attribute of a user, but I don't send a new password or username with it. I use this in my User model:

protected

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

The Password::update method salts and hashes the password for security. The problem is, that whenever I don't specify a password when I save, Rails tries to save an empty password. I use this in my 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

However, my model validates empty passwords, but still a(n) (salted hash of an) empty password gets saved. But it should only save the :profile field if that is the only one given (and the :updated_at field ofcourse).

So I actually mean that when I update the record without specifying the current password, the password attribute is still saved as an hash of an empty string. I want that update_attributes shoul开发者_如何学编程d ignore password if it isn't set.

Can anyone help? Thanks


I'm not totally sure that I understand your problem, but how about adding:

validates_presence_of :password

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


I already found it out myself.

I must check if the password has changed:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜