简体   繁体   English

Rails使用attr_encrypted访问私有方法

[英]Rails accessing private methods using attr_encrypted

I'm trying to get attr_encrypted to obscure some data before saving it to the database. 我正在尝试将attr_encrypted以掩盖某些数据,然后再将其保存到数据库中。 I need to deal with the logger output later, but at the moment I just want to get the field data from a submitted form, encrypt it, and save it. 稍后我需要处理记录器的输出,但是目前,我只想从提交的表单中获取字段数据,对其进行加密并保存。

Here's my model: 这是我的模型:

class Agreement < ApplicationRecord
  attr_encrypted :test_field, key: :encryption_key

  private

  def encryption_key
      ENV['super_secret_key']
  end
end

I notice that when I comment out private everything seems to work as expected. 我注意到当我将private注释掉时,一切似乎都按预期工作。 But I obviously don't want to give public access to that info (ya know: super secret key), so I want it to be private. 但是我显然不想让该信息公开访问(您知道:超级密钥),所以我希望它是私有的。 However, when I include private I get an error. 但是,当我包含private ,会出现错误。 Specifically: NoMethodError (undefined method 'bytesize' for :encryption_key:Symbol) . 具体来说: NoMethodError (undefined method 'bytesize' for :encryption_key:Symbol) What I've drilled down to is that attr_encrypted is throwing an error because it is not getting a key passed to it, because the private method is not being accessed properly. 我深入研究的是attr_encrypted引发错误,因为没有正确地传递私有方法,因为它没有将密钥传递给它。

In theory, in the attr_encrypted bit, I could just set key: ENV['super_secret_key'] rather than calling a method, but the goal here is to actually create a new class with corresponding database table by which I can save, store, and rotate my keys, which in turn are obfuscated by an environment variable for an extra layer of security. 从理论attr_encrypted ,我可以在attr_encrypted位中设置key: ENV['super_secret_key']而不是调用方法,但是这里的目标是实际创建一个具有相应数据库表的新类,通过该类我可以保存,存储和旋转我的密钥,而这些密钥又被环境变量所迷惑,以提供额外的安全保护。

So my real question is: what's going on with my private methods, and why is private frustrating things, even within the scope of the model? 所以我真正的问题是:我的私有方法正在发生什么,为什么private令人沮丧的事情即使在模型范围内也是如此? I think I'm doing something very basically incorrect, but I've also followed examples from others that do this, so any guidance on my error would be greatly appreciated! 我认为我所做的事情基本上很不正确,但是我也参考了其他人的示例,因此,对我的错误提供的任何指导将不胜感激!

The issue is that the attr_encrypted call is at the class level, the encryption_key method is instance level. 问题是attr_encrypted调用是在类级别上,encryption_key方法是在实例级别上。 Try doing this instead: 尝试这样做:

class Agreement < ApplicationRecord
  attr_encrypted :test_field, key: ENV['super_secret_key']]
end

Admittedly untested, but it should work. 公认未经测试,但是应该可以。

Really though the private won't secure it anymore. 确实,尽管私人将不再保护它。 You did this right by loading it through env from a config file. 您可以通过从配置文件通过env加载它来实现此目的。 So long as it's not hardcoded in your repository, that's mainly what you need to do. 只要未在存储库中对其进行硬编码,这主要就是您需要执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM