私は単純なアプリケーションを書いていますが、Rails コンソール内からユーザーのパスワードを更新するのに苦労しています。私はRoR(およびRuby)に非常に慣れていません。私が見逃している単純なものがあると確信しています。モデルと、ターミナルから取得した出力を含めました。
admin_users.rb モデル
require 'digest/sha1'
class AdminUser < ActiveRecord::Base
attr_accessor :password
EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]\.[A-Z]{2,4}$/i
def self.authenticate(username="", password="")
user = AdminUser.find_by_username(username)
if user && user.password_match?(password)
return user
else
return false
end
end
def password_match?(password="")
hashed_password == AdminUser.hash_with_salt(password, salt)
end
validates :first_name, :presence => true, :length => { :maximum => 25 }
validates :last_name, :presence => true, :length => { :maximum => 50 }
validates :username, :presence => true, :length => { :within => 8..25 }, :uniqueness => true
validates :email, :presence => true, :length => { :maximum => 100 }, :uniqueness => true, :format=> EMAIL_REGEX, :confirmation => true
# only on create ,so other attributes of this user can be changed
validates_length_of :password, :within => 8..25, :on => :create
before_save :create_hashed_password
after_save :clear_password
# scope :named, lambda {|first, last| where (:first_name => first, :last_name => last)}
attr_protected :hashed_password, :salt
def self.make_salt(username="")
Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
end
def self.hash_with_salt(password="", salt="")
Digest::SHA1.hexdigest("Put #{salt} on #{password}")
end
private
def create_hashed_password
# Whenever :password has a value, hashing is needed
unless password.blank?
#always use "self" when assigning values
self.salt = AdminUser.make_salt(username) if salt.blank?
self.hashed_password = AdminUser.hash_with_salt(password, salt)
end
end
def clear_password
# for security reasons and because hasing is not needed
self.password = nil
end
end
ターミナル-
user = AdminUser.find(1)
user.password = ('secretpassword')
user.save
次に、ターミナルがこれをくれます...
(0.1ms) BEGIN
AdminUser Exists (0.4ms) SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`username` = BINARY 'benlinus' AND `admin_users`.`id` != 1) LIMIT 1
AdminUser Exists (0.2ms) SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`email` = BINARY 'email.email@me.com' AND `admin_users`.`id` != 1) LIMIT 1
(0.1ms) ROLLBACK
=> false
2.0.0-p195 :018 > user.save
(0.1ms) BEGIN
AdminUser Exists (0.3ms) SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`username` = BINARY 'benlinus' AND `admin_users`.`id` != 1) LIMIT 1
AdminUser Exists (0.2ms) SELECT 1 AS one FROM `admin_users` WHERE (`admin_users`.`email` = BINARY 'email.email@me.com' AND `admin_users`.`id` != 1) LIMIT 1
(0.1ms)
ハングアップがどこにあるのかわかりません。検証でエラーが発生しているようには見えないので、少し混乱しています。