这是我正在使用的.不一定非要听到令牌才能猜测,它更像是一个简短的 url 标识符,而不是其他任何东西,我想保持简短.我已经按照我在网上找到的一些示例进行操作,如果发生冲突,我认为下面的代码将重新创建令牌,但我不确定.不过,我很想看到更好的建议,因为这感觉有点粗糙.
Here's what I'm using. The token doesn't necessarily have to be heard to guess, it's more like a short url identifier than anything else, and I want to keep it short. I've followed some examples I've found online and in the event of a collision, I think the code below will recreate the token, but I'm not real sure. I'm curious to see better suggestions, though, as this feels a little rough around the edges.
def self.create_token random_number = SecureRandom.hex(3) "1X#{random_number}" while Tracker.find_by_token("1X#{random_number}") != nil random_number = SecureRandom.hex(3) "1X#{random_number}" end "1X#{random_number}" end我的令牌数据库列是一个唯一索引,我也在模型上使用 validates_uniqueness_of :token,但因为这些是根据用户在应用程序中的操作自动分批创建的(他们下订单并购买代币,本质上),让应用抛出错误是不可行的.
My database column for the token is a unique index and I'm also using validates_uniqueness_of :token on the model, but because these are created in batches automatically based on a user's actions in the app (they place an order and buy the tokens, essentially), it's not feasible to have the app throw an error.
我想,为了减少冲突的可能性,我还可以在末尾附加另一个字符串,根据时间生成的内容或类似的内容,但我不希望令牌变得太长.
I could also, I guess, to reduce the chance of collisions, append another string at the end, something generated based on the time or something like that, but I don't want the token to get too long.
推荐答案-- 更新 --
截至 2015 年 1 月 9 日.该解决方案现已在 Rails 5 中实施 ActiveRecord 的安全令牌实现.
As of January 9th, 2015. the solution is now implemented in Rails 5 ActiveRecord's secure token implementation.
-- Rails 4 &3 --
仅供将来参考,创建安全的随机令牌并确保模型的唯一性(使用 Ruby 1.9 和 ActiveRecord 时):
Just for future reference, creating safe random token and ensuring it's uniqueness for the model (when using Ruby 1.9 and ActiveRecord):
class ModelName < ActiveRecord::Base before_create :generate_token protected def generate_token self.token = loop do random_token = SecureRandom.urlsafe_base64(nil, false) break random_token unless ModelName.exists?(token: random_token) end end end@kain 建议,我同意,替换 begin...end...whilecode> with loop do...break until...end 在这个答案中,因为以前的实现可能会在未来被删除.
@kain suggested, and I agreed, to replace begin...end..while with loop do...break unless...end in this answer because previous implementation might get removed in the future.
编辑 2:
对于 Rails 4 和关注点,我建议将其移至关注点.
With Rails 4 and concerns, I would recommend moving this to concern.
# app/models/model_name.rb class ModelName < ActiveRecord::Base include Tokenable end # app/models/concerns/tokenable.rb module Tokenable extend ActiveSupport::Concern included do before_create :generate_token end protected def generate_token self.token = loop do random_token = SecureRandom.urlsafe_base64(nil, false) break random_token unless self.class.exists?(token: random_token) end end end更多推荐
在 Rails 中创建唯一令牌的最佳方法?
发布评论