在我的应用中,管理员仅使用电子邮件创建用户。用户尝试设置密码时不起作用。下面的代码仅在我删除验证时有效。
def password=(password_str)
@password = password_str
self.password_salt = BCrypt::Engine.generate_salt
self.password_digest = BCrypt::Engine.hash_secret(password_str, password_salt)
end
def authenticate(password)
password.present? && password_digest.present? && password_digest == BCrypt::Engine.hash_secret(password, password_salt)
end
validates :password , length: { minimum: 6 }, :if => :setting_password?
validates :password_confirmation, presence: true , :if => :setting_password?
def setting_password?
self.password || self.password_confirmation
end
1)我只有在评论密码验证时才能设置密码
2)password_confirmation字段按原样保存密码。
对于大多数身份验证类型(以及我大部分时间使用的身份验证)而言,这是一个有用的解决方案,但是如果您确实需要在没有has_secure_password的情况下编写身份验证,那么Ryan Bates的Railscasts可以满足您的要求。
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
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
end
对于rails 4,这是不同的(模型上没有更多的attr_accessors),对此进行修改,我们需要一个attr_reader:password以及一种设置密码和password_confirmation的方式,以便:
class User < ActiveRecord::Base
attr_reader :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
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
##
# accessor
def password=(unencrypted_password)
unless unencrypted_password.blank?
@password = unencrypted_password
end
end
##
# accessor
def password_confirmation=(unencrypted_password)
@password_confirmation = unencrypted_password
end
end
但是,如果我们在这里查看has_secure_password方法,则会发现业务逻辑位于password =(未加密)中,而不是保存前的回调中(这很明显),我认为这可能是执行此操作的最干净的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句