在 Rails 应用程序中混淆 id
我试图混淆离开服务器的所有 id,即出现在 URL 和 HTML 输出中的 id。
我编写了一个简单的 Base62 库,其中包含编码和解码方法。定义(或者更好)覆盖 ActiveRecord 的 id 方法以返回 id 的编码版本,并调整控制器以使用解码后的 params[:id] 加载资源给我带来了所需的结果。 id 现在在 url 中进行了 base62 编码,并且响应显示了正确的资源。
现在我开始注意到通过 has_many
关系定义的子资源未加载。例如,我有一个名为 User
的记录,其中 has_many
Post
。现在,尽管有 user_id = 1
的帖子,但 User.find(1).posts
为空。我的解释是,ActiveRecord 必须将 Post
的 user_id
与 User< 的 method
id
进行比较/code>——我已经覆盖了——而不是与 self[:id]
进行比较。所以基本上这使得我的方法毫无用处。
我想要的是在模型中定义 obfuscates_id ,其余的将被处理,即在适当的位置进行所有编码/解码并防止 id 返回服务器。
有没有可用的宝石或者有人提示如何实现这一点?我敢打赌我不是第一个尝试这个的人。
I'm trying to obfuscate all the ids that leave the server, i.e., ids appearing in URLs and in the HTML output.
I've written a simple Base62 lib that has the methods encode and decode. Defining—or better—overwriting the id method of an ActiveRecord to return the encoded version of the id and adjusting the controller to load the resource with the decoded params[:id]
gives me the desired result. The ids now are base62 encoded in the urls and the response displays the correct resource.
Now I started to notice that subresources defined through has_many
relationships aren't loading. e.g. I have a record called User
that has_many
Post
s. Now User.find(1).posts
is empty although there are posts with user_id = 1
. My explanation is that ActiveRecord must be comparing the user_id
of Post
with the method id
of User
—which I've overwritten—instead of comparing with self[:id]
. So basically this renders my approach useless.
What I would like to have is something like defining obfuscates_id
in the model and that the rest would be taken care of, i.e., doing all the encoding/decoding at the appropriate locations and preventing ids to be returned by the server.
Is there any gem available or does somebody have a hint how to accomplish this? I bet I'm not the first trying this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所描述的内容听起来像是 URL slug 的专门应用程序。看一下像acts_as_sluggable 或Friendly_id 这样的插件。另请参阅重写 User 模型上的 to_param 方法。
也许从这里开始:Rails 的最佳永久链接
What you are describing sounds like a specialized application of a URL slug. Take a look at plugins like acts_as_sluggable or friendly_id. Also look at overriding the to_param method on your User model.
Maybe start here: Best Permalinking for Rails