ApiKey

ApiKeyDatabase extends ApiKeyMemory
in package

class ApiKeyDatabase: Manages API keys, extending the in-memory storage with database persistence using `PDO`.

This class provides functionality to create, save, and load API keys from a database. It can utilizes any PDO database for storage and requires a PDO instance to be available. The database schema is automatically created if it doesn't exist.

Tags
since
0.0.1

Table of Contents

Properties

$created  : int
$data  : string
$debug  : bool
A static flag to enable or disable debug output.
$hashed_public_key  : string
$ip  : string
$label  : string
$pdo  : PDO|null
$public_key  : string
The public key associated with this Key object.
$tableName  : string
$ttl  : int
$APP_KEY  : string
$HASH_ALGO  : string
$KEY_LENGTH  : int
$memory  : array<string|int, mixed>

Methods

__construct()  : mixed
Key constructor.
anatomy()  : array<string|int, mixed>
Analyzes a token and provides its anatomy in relation to a given Key object.
check()  : bool
Checks if a given API token is valid by retrieving the corresponding key from memory.
create()  : self
Creates a new Key object with pre-defined hashed public key and data.
dict()  : array<string|int, mixed>
Returns an associative array representing the Key object's label, IP address, and data.
file()  : string
Constructs a file path based on a given timestamp and an optional filename.
file_path()  : string
Generates the specific file path for this instance's data storage.
hmac()  : string
Computes the HMAC (Hash-based Message Authentication Code) of a given text.
make()  : Key
Generates a new API key, saves it in memory, and returns the token.
parse()  : array<string|int, mixed>
Parses a token to extract the public key and the shared key (HMAC of the private key).
test()  : void
Performs a basic test of the API key functionality.
token()  : string
Generates a token by concatenating the public key and the HMAC of the private key.
valid()  : bool
Validates a given token against the current Key object's private key and application key.
load()  : array<string|int, mixed>|null
Loads a key's data from the in-memory storage based on its hashed public key.
save()  : bool
Saves a Key object's data into the in-memory storage.
data()  : string
Manages the internal data of the object, allowing retrieval in hexadecimal format or setting it from a hexadecimal string.
private_key()  : array<string|int, mixed>
Extracts the private key from the `$data` property.
random_key()  : string
Generates a random key of the specified length.

Properties

$created

public int $created = 0

$debug

A static flag to enable or disable debug output.

public static bool $debug = false

Defaults to false.

Tags
since
0.0.1

$hashed_public_key

public string $hashed_public_key = ''

$pdo

public static PDO|null $pdo = NULL

PDO instance for database interaction.

Tags
since
0.0.1

$public_key

The public key associated with this Key object.

public string $public_key
Tags
since
0.0.1

$tableName

public static string $tableName = 'api_keys'

The name of the database table used to store API keys. Defaults to 'api_keys'.

Tags
since
0.0.1

$APP_KEY

private string $APP_KEY

$HASH_ALGO

private string $HASH_ALGO = API_KEY_DEFAULT_ALGO

$KEY_LENGTH

private int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH

$memory

private static array<string|int, mixed> $memory = []

A static array that holds the API keys in memory. The keys of this array are the hashed public keys, and the values are arrays representing the key data.

Tags
since
0.0.1

Methods

__construct()

Key constructor.

public __construct(string $label, string $ip, string $APP_KEY[, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ][, string $hashed_public_key = '' ][, string $data = '' ][, int $created = 0 ][, int $ttl = 0 ]) : mixed

Initializes a new Key object. If $hashed_public_key or $data are not provided, it generates a new public key, a corresponding hashed public key, and associated data.

Parameters
$label : string

A label for this key.

$ip : string

The IP address associated with this key.

$APP_KEY : string

The application-specific secret key used for hashing. This is required.

$KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH

The length of the generated random keys in bytes. Defaults to API_KEY_DEFAULT_LENGTH.

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm to use for HMAC. Defaults to API_KEY_DEFAULT_ALGO. Must be a supported algorithm by hash_hmac_algos().

$hashed_public_key : string = ''

An optional pre-computed hashed public key.

$data : string = ''

Optional pre-existing data associated with the key.

$created : int = 0

Optional pre-existing creation timestamp. If not provided.

$ttl : int = 0

The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.

Tags
throws
Exception

If $APP_KEY is empty or if the $HASH_ALGO is not supported.

since
0.0.1

anatomy()

Analyzes a token and provides its anatomy in relation to a given Key object.

public static anatomy(string $token, Key $key) : array<string|int, mixed>
Parameters
$token : string

The token to analyze.

$key : Key

The Key object to compare against.

Tags
since
0.0.1
Return values
array<string|int, mixed>

An associative array containing the token, extracted public key, shared key, the Key object's public key and hashed public key, the Key object's data, and a boolean indicating if the token is valid for the given Key object.

check()

Checks if a given API token is valid by retrieving the corresponding key from memory.

public static check(string $token[, string $ip = '' ][, string $APP_KEY = APP_KEY ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : bool
Parameters
$token : string

The API token to check.

$ip : string = ''

The IP address associated with this key (optional, defaults to '').

$APP_KEY : string = APP_KEY

The application-specific secret key used for signing (defaults to the global APP_KEY constant).

$KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH

The expected length of the public and private keys (defaults to API_KEY_DEFAULT_LENGTH).

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm used (defaults to API_KEY_DEFAULT_ALGO).

Tags
since
0.0.1
Return values
bool

Returns true if the token is valid, false otherwise.

create()

Creates a new Key object with pre-defined hashed public key and data.

public static create(string $hashed_public_key, string $data, string $APP_KEY[, string $label = '' ][, string $ip = '' ][, int $ttl = 0 ][, int $created = 0 ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : self

This static method is useful for reconstructing a Key object from stored data.

Parameters
$hashed_public_key : string

The pre-computed hashed public key.

$data : string

The pre-existing data associated with the key.

$APP_KEY : string

The application-specific secret key used for hashing.

$label : string = ''

An optional label for this key. Defaults to an empty string.

$ip : string = ''

The IP address associated with this key. Defaults to an empty string.

$ttl : int = 0

The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.

$created : int = 0

Optional pre-existing creation timestamp. If not provided.

$KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH

The length of the original random keys in bytes. Defaults to API_KEY_DEFAULT_LENGTH.

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm used for HMAC. Defaults to API_KEY_DEFAULT_ALGO.

Tags
since
0.0.1
Return values
self

A new Key object initialized with the provided data.

dict()

Returns an associative array representing the Key object's label, IP address, and data.

public dict() : array<string|int, mixed>
Tags
since
0.0.1
Return values
array<string|int, mixed>

An associative array with keys 'label', 'ip', and 'data'.

file()

Constructs a file path based on a given timestamp and an optional filename.

public static file(int $created[, string $file = '' ]) : string

This static method generates a directory structure using the year, month, and day extracted from the provided timestamp. The resulting path can optionally include a filename at the end.

Parameters
$created : int

A timestamp representing the creation date. This timestamp is expected to be an integer with a length of 8 digits (YYYYMMDD format). An assertion will fail if this condition is not met.

$file : string = ''

An optional filename to append to the generated directory path. Defaults to an empty string.

Tags
throws
AssertionError

If the $created timestamp is not a non-zero integer or if its string representation does not have a length of 8 characters.

since
0.0.1
Return values
string

The generated file path, with directory separators appropriate for the operating system. The path will be in the format: YYYY/MM/DD[/filename].

file_path()

Generates the specific file path for this instance's data storage.

public file_path() : string

This method leverages the file() static method to create a structured file path. The path is determined by the instance's creation timestamp and a unique identifier derived from its hashed public key. This strategy ensures a well-organized and distributed storage system.

Tags
throws
AssertionError

If the hashed_public_key property of this instance is not yet set (i.e., is falsy).

since
0.0.1
Return values
string

The generated file path. The path is composed of subdirectories representing the year, month, and day of creation, followed by the instance's hashed public key as the filename. The directory separators are platform-specific.

hmac()

Computes the HMAC (Hash-based Message Authentication Code) of a given text.

public static hmac(string $text, string $APP_KEY[, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : string
Parameters
$text : string

The input string to hash.

$APP_KEY : string

The secret key to use for the HMAC.

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm to use. Defaults to API_KEY_DEFAULT_ALGO.

Tags
since
0.0.1
Return values
string

The hexadecimal representation of the HMAC.

make()

Generates a new API key, saves it in memory, and returns the token.

public static make(string $label[, string $ip = '' ][, int $ttl = 0 ][, string $APP_KEY = APP_KEY ][, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : Key
Parameters
$label : string

A descriptive label for the API key.

$ip : string = ''

The IP address associated with this key (optional, defaults to '').

$ttl : int = 0

The time-to-live (in seconds) for this key. After this duration, the key is considered expired. A value of 0 indicates that the key never expires. Defaults to 0.

$APP_KEY : string = APP_KEY

The application-specific secret key used for signing (defaults to the global APP_KEY constant).

$KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH

The desired length of the public and private keys (defaults to API_KEY_DEFAULT_LENGTH).

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm to use (defaults to API_KEY_DEFAULT_ALGO).

Tags
since
0.0.1
Return values
Key

The generated API token object.

parse()

Parses a token to extract the public key and the shared key (HMAC of the private key).

public static parse(string $token[, int $KEY_LENGTH = API_KEY_DEFAULT_LENGTH ][, string $HASH_ALGO = API_KEY_DEFAULT_ALGO ]) : array<string|int, mixed>
Parameters
$token : string

The token to parse.

$KEY_LENGTH : int = API_KEY_DEFAULT_LENGTH

The expected length of the public key in bytes. Defaults to API_KEY_DEFAULT_LENGTH.

$HASH_ALGO : string = API_KEY_DEFAULT_ALGO

The hashing algorithm that was used to generate the HMAC. Defaults to API_KEY_DEFAULT_ALGO.

Tags
throws
Exception

If the $HASH_ALGO is not supported.

since
0.0.1
Return values
array<string|int, mixed>

An array containing the public key (at index 0) and the shared key (at index 1), or an empty array if the token format is invalid or the hash algorithm is unsupported.

test()

Performs a basic test of the API key functionality.

public static test([bool $debug = false ]) : void

This method defines constants for the API key path and application key, enables debugging if requested, creates a new API key, and then performs basic assertions to check if the key generation and validation work as expected.

Parameters
$debug : bool = false

Optional. If true, enables debugging output. Defaults to false.

Tags
since
0.0.1

token()

Generates a token by concatenating the public key and the HMAC of the private key.

public token() : string
Tags
throws
AssertionFailedError

If $this->public_key is empty in non-debug mode.

since
0.0.1
Return values
string

The generated token.

valid()

Validates a given token against the current Key object's private key and application key.

public valid(string $token[, string $ip = '' ]) : bool
Parameters
$token : string

The token to validate.

$ip : string = ''

The IP address associated with this key. Defaults to an empty string.

Tags
since
0.0.1
Return values
bool

True if the token is valid, false otherwise.

load()

Loads a key's data from the in-memory storage based on its hashed public key.

protected static load(string $hashed_public_key, int $created) : array<string|int, mixed>|null
Parameters
$hashed_public_key : string

The hashed version of the public key to look up.

$created : int

pre-existing creation timestamp. If not provided.

Tags
since
0.0.1
Return values
array<string|int, mixed>|null

Returns an array containing the key's data if found, otherwise NULL.

save()

Saves a Key object's data into the in-memory storage.

protected static save(Key $key) : bool
Parameters
$key : Key

The Key object to save.

Tags
since
0.0.1
Return values
bool

Returns true if the key was successfully saved.

data()

Manages the internal data of the object, allowing retrieval in hexadecimal format or setting it from a hexadecimal string.

private data([string $data_hex = '' ]) : string

When called without any arguments, this method decodes the internal base64 encoded data and returns its hexadecimal representation.

When called with a hexadecimal string as an argument, it encodes this string into base64 and updates the internal data of the object. In this case, the method returns an empty string.

Parameters
$data_hex : string = ''

Optional. A hexadecimal string to set as the internal data. Defaults to an empty string, in which case the current data is returned in hexadecimal format.

Tags
since
0.0.1
Return values
string

The hexadecimal representation of the internal data if no argument is provided. An empty string if a hexadecimal string is provided as an argument.

private_key()

Extracts the private key from the `$data` property.

private private_key() : array<string|int, mixed>

This function assumes that the $data property has a specific structure: random bytes (1 to KEY_LENGTH) + hashed public key + private key + random bytes (1 to KEY_LENGTH). It extracts the private key based on the position of the $hashed_public_key.

Tags
throws
AssertionFailedError

If the length of $this->data is less than four times $this->KEY_LENGTH in non-debug mode.

since
0.0.1
Return values
array<string|int, mixed>

The extracted private key with IP.

random_key()

Generates a random key of the specified length.

private random_key() : string
Tags
since
0.0.1
Return values
string

A hexadecimal representation of the random key.


        
On this page

Search results