簡體   English   中英

更新用戶模型會重置密碼嗎? Rails問題

[英]Updating a User model resets password? Rails question

在我的控制器中,我嘗試更新用戶實例的rank屬性(整數)。 例如1到2。

我這樣做是:

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

由於某種原因,保存的用戶的密碼會被刪除,因此他們完全無需密碼即可登錄我的網站。 我嘗試了和沒有:validate => false參數。

有什么原因嗎? 救命? 謝謝一大堆

型號代碼

類User <ActiveRecord :: Base attr_accessor:password attr_accessible:login,:email,:fname,:lname,:password,:password_confirmation,:rank,:hours,:wars email_filter = /\\A[\\w+-.]+@ [az \\ d-。] +。[az] + \\ 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

結束

您只想在存在密碼的情況下對密碼進行加密,因此請在回調中添加一個條件

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

另外,您不想每次更新用戶記錄時都驗證密碼。 您可以刪除:presence => true驗證,並添加一個條件以僅在輸入密碼時運行其他驗證。

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

我知道現在已經很晚了,但實際上我只是偶然發現了於2009年寫在therailsways.com上的這篇文章,但是仍然可以為我工作,以防其他任何通過Google來到這里的人遇到同樣的問題。

before_save :encrypt_password, :if => :password_changed?

我遇到了同樣的問題,我的密碼將在更新時重新加密,但是我只想在創建用戶時對其進行加密。

我一直在尋找before_save替代方法,但沒有一個真正做到了。 但是,確實可以做到這一點,我所要做的就是添加if條件。 效果很好。

您有一個before_filter ,可以在每次保存模型時對密碼進行加密。 代替before_filter使用如下代碼:

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

暫無
暫無

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

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