Module: Securial::Auth::TokenGenerator

Extended by:
TokenGenerator
Included in:
TokenGenerator
Defined in:
lib/securial/auth/token_generator.rb

Overview

Generates secure tokens for authentication operations.

This module provides methods to generate cryptographically secure tokens for different authentication scenarios. All tokens use secure random generation and appropriate cryptographic techniques to ensure uniqueness and security.

Instance Method Summary collapse

Instance Method Details

#friendly_token(length = 20) ⇒ String

Generates a URL-safe friendly token for general use.

Creates a secure, URL-safe token suitable for various authentication operations that require a balance between security and usability.

Examples:

token = TokenGenerator.friendly_token
# => "aBcDeF123456GhIjKl78"

With custom length

token = TokenGenerator.friendly_token(32)
# => "aBcDeF123456GhIjKl789012MnOpQr34"

Parameters:

  • length (Integer) (defaults to: 20)

    The desired length of the generated token (default: 20)

Returns:

  • (String)

    A URL-safe token containing letters, numbers, and safe symbols



95
96
97
# File 'lib/securial/auth/token_generator.rb', line 95

def friendly_token(length = 20)
  SecureRandom.urlsafe_base64(length).tr("lIO0", "sxyz")[0, length]
end

#generate_password_reset_tokenString

Note:

This token has lower entropy than refresh tokens and should have shorter expiration times and rate limiting protection.

Generates a user-friendly password reset token.

Creates a short, alphanumeric token formatted for easy user entry. The token is suitable for password reset flows where users need to manually enter the token from an email or SMS message.

Examples:

token = TokenGenerator.generate_password_reset_token
# => "aBc123-DeF456"

Returns:

  • (String)

    A formatted password reset token (format: “ABC123-DEF456”)

See Also:



74
75
76
77
# File 'lib/securial/auth/token_generator.rb', line 74

def generate_password_reset_token
  token = SecureRandom.alphanumeric(12)
  "#{token[0, 6]}-#{token[6, 6]}"
end

#generate_refresh_tokenString

Generates a secure refresh token using HMAC and random data.

Creates a refresh token by combining an HMAC signature with random data, providing both integrity verification and sufficient entropy. The token is suitable for long-term storage and session refresh operations.

Examples:

token = TokenGenerator.generate_refresh_token
# => "a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456789012345678901234567890abcdef"

Returns:

  • (String)

    A secure refresh token (96 characters hexadecimal)

See Also:



46
47
48
49
50
51
52
53
54
55
# File 'lib/securial/auth/token_generator.rb', line 46

def generate_refresh_token
  secret = Securial.configuration.session_secret
  algo = "SHA256"

  random_data = SecureRandom.hex(32)
  digest = OpenSSL::Digest.new(algo)
  hmac = OpenSSL::HMAC.hexdigest(digest, secret, random_data)

  "#{hmac}#{random_data}"
end