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.

Class Method Summary collapse

Class Method Details

.call(length: ApiKeys.configuration.token_length, prefix: ApiKeys.configuration.token_prefix.call, alphabet: ApiKeys.configuration.token_alphabet) ⇒ String

Generates a new token string.

Parameters:

  • length (Integer) (defaults to: ApiKeys.configuration.token_length)

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

  • prefix (String) (defaults to: ApiKeys.configuration.token_prefix.call)

    The prefix to prepend to the token.

  • alphabet (Symbol) (defaults to: ApiKeys.configuration.token_alphabet)

    The encoding alphabet (:base58 or :hex).

Returns:

  • (String)

    The generated token including the prefix.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/api_keys/services/token_generator.rb', line 16

def self.call(length: ApiKeys.configuration.token_length, prefix: ApiKeys.configuration.token_prefix.call, alphabet: ApiKeys.configuration.token_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