module ActiveRecord::SecureToken::ClassMethods
Общедоступные методы экземпляров
# File activerecord/lib/active_record/secure_token.rb, line 43 def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) SecureRandom.base58(length) end
# File activerecord/lib/active_record/secure_token.rb, line 32
def has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH)
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) }
before_create { send("#{attribute}=", self.class.generate_unique_secure_token(length: length)) unless send("#{attribute}?") }
end Пример использования 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. Рекомендуется добавить уникальный индекс в базу данных, чтобы справиться с этой еще более маловероятной ситуацией.
© 2004–2020 David Heinemeier Hansson
Licensed under the MIT License.