Class: ApiKeys::Services::TokenGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/api_keys/services/token_generator.rb

Overview

Generates secure, random API tokens according to configured settings.

Constant Summary collapse

MIN_RANDOM_BYTES =
16
MAX_RANDOM_BYTES =
64
MAX_PREFIX_BYTESIZE =
64

Class Method Summary collapse

Class Method Details

.call(length: nil, prefix: nil, alphabet: nil) ⇒ String

Generates a new token string.

Parameters:

  • length (Integer) (defaults to: nil)

    The desired byte length of the random part (before encoding).

  • prefix (String) (defaults to: nil)

    The prefix to prepend to the token.

  • alphabet (Symbol) (defaults to: nil)

    The encoding alphabet (:base58 or :hex).

Returns:

  • (String)

    The generated token including the prefix.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/api_keys/services/token_generator.rb', line 20

def self.call(length: nil, prefix: nil, alphabet: nil)
  length ||= ApiKeys.configuration.token_length
  prefix ||= ApiKeys.configuration.resolved_token_prefix
  alphabet ||= ApiKeys.configuration.token_alphabet

  validate_length!(length)
  validate_prefix!(prefix)
  validate_alphabet!(alphabet)

  random_bytes = SecureRandom.bytes(length)

  random_part = case alphabet
                when :base58
                  Base58.binary_to_base58(random_bytes, :bitcoin)
                when :hex
                  random_bytes.unpack1("H*") # Equivalent to SecureRandom.hex
                else
                  raise ArgumentError, "Unsupported token alphabet: #{alphabet}. Use :base58 or :hex."
                end

  "#{prefix}#{random_part}"
end