跳到內容 跳到搜尋
方法
G
H

Instance 共用方法

generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH)

# 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 字元的唯一 Token,因此發生衝突的機率極低。

請注意,類似於 validates_uniqueness_of 在資料庫中產生競爭條件的可能性仍然存在。建議您在資料庫中新增唯一索引,來處理更不可能發生的這個案例。

選項

:length

安全隨機數的長度,至少為 24 個字元。預設為 24。

:on

產生值時的回呼。當使用 on: :initialize 呼叫時,該值會在 after_initialize 回呼中產生,否則,值會使用在 before_ 回呼中。未指定時,:on 會使用 config.active_record.generate_secure_token_on 的值,該值從 Rails 7.1 開始預設為 :initialize

# 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