Documentation
¶
Index ¶
Constants ¶
View Source
const ( // EnvLive represents production environment EnvLive = "live" // EnvTest represents test environment EnvTest = "test" // KeyPrefix is the prefix for all API keys KeyPrefix = "pk_" // SecretLength is the length of the random secret part SecretLength = 32 )
Variables ¶
View Source
var ( // ErrInvalidFormat indicates the API key format is invalid ErrInvalidFormat = errors.New("invalid API key format") // ErrInvalidEnvironment indicates the environment is invalid ErrInvalidEnvironment = errors.New("invalid environment, must be 'live' or 'test'") )
Functions ¶
func CompareSecret ¶
CompareSecret verifies an API key against its bcrypt hash.
Example:
valid := CompareSecret(hash, "pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6")
Parameters:
- hash: The bcrypt hash stored in database
- key: The API key to verify
Returns:
- bool: true if the key matches the hash, false otherwise
func ExtractEnvironment ¶
ExtractEnvironment extracts the environment from an API key.
Example:
env, err := ExtractEnvironment("pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6")
// env = "live"
Parameters:
- key: The API key
Returns:
- string: Environment ("live" or "test")
- error: Error if key format is invalid
func GenerateAPIKey ¶
GenerateAPIKey generates a secure API key with format: pk_{env}_{32_char_base64} Similar to Stripe's API key format.
Example:
- Live: pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
- Test: pk_test_x9y8z7w6v5u4t3s2r1q0p9o8n7m6l5k4
Parameters:
- env: Environment type ("live" or "test")
Returns:
- string: Generated API key
- error: Error if generation fails
func HashSecret ¶
HashSecret hashes the API key using bcrypt for secure storage. The cost factor is set to bcrypt.DefaultCost (10).
Example:
hash, err := HashSecret("pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6")
Parameters:
- key: The API key to hash
Returns:
- string: Bcrypt hash of the API key
- error: Error if hashing fails
func ValidateFormat ¶
ValidateFormat validates that an API key has the correct format. Expected format: pk_{env}_{base64_secret}
Example:
err := ValidateFormat("pk_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6")
Parameters:
- key: The API key to validate
Returns:
- error: ErrInvalidFormat if format is invalid, nil otherwise
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.