方法
实例公共方法
generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) 链接
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/secure_token.rb, line 61 def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) SecureRandom.base58(length) end
has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH, on: ActiveRecord.generate_secure_token_on) 链接
使用 has_secure_token 的示例
# Schema: User(token:string, auth_token:string) class User < ActiveRecord::Base has_secure_token has_secure_token :auth_token, length: 36 end user = User.new user.save user.token # => "pX27zsMN2ViQKta1bGfLmVJE" user.auth_token # => "tU9bLuZseefXQ4yQxQo8wjtBvsAfPc78os6R" user.regenerate_token # => true user.regenerate_auth_token # => true
SecureRandom::base58 用于生成至少 24 个字符的唯一令牌,因此发生冲突的可能性极小。
请注意,生成数据库中的竞态条件仍有可能发生,就像 validates_uniqueness_of 会发生一样。建议在数据库中添加唯一索引来处理这种更不可能发生的情况。
选项¶ ↑
:length-
安全随机数的长度,最小为 24 个字符。默认为 24。
:on-
生成值的回调。当调用
on: :initialize时,该值在after_initialize回调中生成,否则该值将用于before_回调。如果未指定,:on将使用config.active_record.generate_secure_token_on的值,从 Rails 7.1 开始,该值默认为:initialize。
来源: 显示 | 在 GitHub 上
# File activerecord/lib/active_record/secure_token.rb, line 46 def has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH, on: ActiveRecord.generate_secure_token_on) if length < MINIMUM_TOKEN_LENGTH raise MinimumLengthError, "Token requires a minimum length of #{MINIMUM_TOKEN_LENGTH} characters." end # Load securerandom only when has_secure_token is used. require "active_support/core_ext/securerandom" define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token(length: length) } set_callback on, on == :initialize ? :after : :before do if new_record? && !query_attribute(attribute) send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) end end end