【问题标题】:Overriding attributes of Ohm models欧姆模型的覆盖属性
【发布时间】:2014-10-06 22:41:34
【问题描述】:

我遇到了一个非常奇怪的 Ohm 问题,我无法跟踪和解决。 欧姆版本是 2.0.1。

这是我的代码:

class User < Ohm::Model
  attribute :username
  attribute :password

  index :username

  def password= string
    @attributes[:password] = BCrypt::Password.create(string) # Tried self.password = BCrypt::whatever too
  end
end

[15] pry(main)> User.find(username: 'test').first.password
=> "$2a$10$j1.s4hmuyCm8RffaEvB8IejaYOiZXWXId1Ccf8S0K3uXduxmMzyUq"
[16] pry(main)> User.find(username: 'test').first.password
=> "$2a$10$/0UzWtVsF.xczf4.UUqrP.PqYHxKs8fkIWKHlVVQVUNPFubzmuCwO"
[17] pry(main)> User.find(username: 'test').first.password
=> "$2a$10$ajlc3BYMOFXYDmy1a112ieXhMm39KoR1wPdPMp4WwEnxb2E35ypvC"
[18] pry(main)> User.find(username: 'test').first.password
=> "$2a$10$TlW87Gpd4RKpPutWzkePqeQiGri2ah.txDda4o6Lki7Sk1vayY9Fm"

基本上我可以设置密码并使用 BCrypt 对其进行加密,但由于某些原因,每次我调用属性时密码都是不同的。 我不知道这里发生了什么,有人可以帮助我吗?

【问题讨论】:

    标签: ruby redis sinatra ohm


    【解决方案1】:

    当 Ohm 从数据库加载属性时,它不会分配它 直接@attributes。相反,它使用访问器来允许 任何类型的类型铸造。在你的情况下,发生的事情是每个 当 Ohm 从 Redis 加载密码字段时,它会再次处理它 与 BCrypt。你可以check the code in question。

    我通常做的有点不同:我定义一个属性 crypted_password 欧姆,然后在模型中我定义了一个方法 password= 接受一个字符串并生成加密版本, 然后将其存储在crypted_password 属性中。我用宝石 叫盾,here's the relevant code。

    您可以做类似于 Shield 所做的事情,并使用 BCrypt 反而。您必须定义一个属性crypted_password,然后 名为password= 的方法与您的方法有点不同 目前有:

    class User < Ohm::Model
      attribute :username
      attribute :crypted_password
    
      index :username
    
      def password= string
        self.crypted_password = BCrypt::Password.create(string)
      end
    end
    

    应该可以,您必须使用crypted_password 验证用户。

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多