更新用户模型会重置密码吗? Rails问题

时间:2011-08-25 13:18:13

标签: ruby-on-rails ruby ruby-on-rails-3

在我的控制器中,我尝试更新用户实例的rank属性(整数)。例如从1到2。

我是这样做的:

@user = User.find(params[:id])
@user.rank = 2
@user.save(:validate => false)

由于某种原因,正在保存的用户的密码被删除,因此他们可以在没有密码的情况下登录我的网站。我已尝试使用和不使用:validate => false参数。

有什么理由?救命?非常感谢

型号代码

class User<的ActiveRecord :: Base的     attr_accessor:密码     attr_accessible:login,:email,:fname,:lname,:password,:password_confirmation,:rank,:hours,:wars     email_filter = / \ A [\ w + - 。] + @ [a-z \ d - 。] +。[a-z] + \ z / i

validates :login, :presence => true, :length => { :maximum => 15, :minimum => 4 }, :uniqueness => true
validates :fname, :presence => true, :length => {:minimum => 2 }
validates :lname, :presence => true, :length => {:minimum => 2 }
validates :email, :presence => true, :format => { :with => email_filter}, :uniqueness => { :case_sensitive => false }
validates :password,  :presence => true, :confirmation => true, :length => { :within =>4..40 }
validates :lane_id, :presence => true

before_save :encrypt_password
has_many :reports
has_many :accomplishments
belongs_to :lane 


def has_password?(submitted_password)
  encrypted_password == encrypt(submitted_password)
end

def self.authenticate(login, submitted_password)
  user = find_by_login(login)
  return nil  if user.nil?
  return user if user.has_password?(submitted_password)
end

def self.authenticate_with_salt(id, cookie_salt)
  user = find_by_id(id)
  (user && user.salt == cookie_salt) ? user : nil
end

def current_report
  report = (Report.order("created_at DESC")).find_by_user_id(@user.id)
end

private

def encrypt_password
  self.salt = make_salt if new_record?
  self.encrypted_password = encrypt(password)
end

def encrypt(string)
  secure_hash("#{salt}--#{string}")
end

def make_salt
  secure_hash("#{Time.now.utc}--#{password}")
end

def secure_hash(string)
  Digest::SHA2.hexdigest(string)
end

2 个答案:

答案 0 :(得分:3)

如果存在密码,您只想加密密码,因此为回调添加条件

before_save :encrypt_password, :unless => "password.blank?"

此外,您不希望每次更新用户记录时都验证密码。您可以删除:presence => true验证,并添加条件以仅在密码存在时运行其他验证。

validates :password,  :confirmation => true, :length => { :within =>4..40 }, :unless => "password.blank?"

答案 1 :(得分:0)

每次保存模型时,您都有before_filter加密密码。而不是before_filter使用这样的东西:

def password=(new_password)
  self.salt = make_salt if new_record?
  self.encrypted_password = encrypt(new_password)
end