Ruby on Rails设计主密码

时间:2016-04-14 13:17:08

标签: ruby-on-rails ruby devise

我尝试使用我的用户模型为Devise实现主密码功能,但在关注wiki article后,我在尝试启动rails服务器时遇到以下错误:



/Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:324:in `Integer': can't convert Hash into Integer (TypeError)
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb:324:in `sanitize_limit'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/query_methods.rb:856:in `build_arel'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/query_methods.rb:842:in `arel'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:611:in `exec_queries'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:493:in `load'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation.rb:238:in `to_a'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/finder_methods.rb:474:in `find_nth_with_limit'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/relation/finder_methods.rb:130:in `first'
	from /Users/godzilla/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activerecord-4.1.7/lib/active_record/querying.rb:3:in `first'
	from /Users/godzilla/Documents/Coding/app-api/app/models/user.rb:142:in `<class:User>'
	from /Users/godzilla/Documents/Coding/app-api/app/models/user.rb:1:in `<top (required)>'
&#13;
&#13;
&#13;

因此,它表示我的用户模型中的第142行存在错误。目前,我只是直接从维基中剪切并粘贴代码以实现实现。

模型/ user.rb

&#13;
&#13;
def valid_password?(password)
  return true if valid_master_password?(password)
  super
end

DEFAULT_MASTER_USER_EMAIL = 'auser@mydomain.com' 
DEFAULT_MASTER_USER = self.first(email: DEFAULT_MASTER_USER_EMAIL)
DEFAULT_ENCRYPTED_MASTER_PASSWORD = DEFAULT_MASTER_USER.try(:encrypted_password)

def valid_master_password?(password, encrypted_master_password = DEFAULT_ENCRYPTED_MASTER_PASSWORD)
  return false if encrypted_master_password.blank?
  bcrypt_salt = ::BCrypt::Password.new(encrypted_master_password).salt
  bcrypt_password_hash = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt_salt)
  Devise.secure_compare(bcrypt_password_hash, encrypted_master_password)
end
&#13;
&#13;
&#13;

我需要做些什么来让这个工作吗?根据Devise的说法,它应该是一个千篇一律的实现。

1 个答案:

答案 0 :(得分:0)

我最后改变了:

DEFAULT_MASTER_USER = self.first(email: DEFAULT_MASTER_USER_EMAIL)

DEFAULT_MASTER_USER = self.find_by(email: DEFAULT_MASTER_USER_EMAIL)

因为它试图通过电子邮件地址进行查找,而不是id。立即行动。