Add names to API tokens.

This commit is contained in:
2026-05-18 22:22:14 +02:00
parent 30cbb0e1c7
commit 995eca4111
6 changed files with 25 additions and 14 deletions

View File

@@ -30,14 +30,15 @@ class API_apitoken extends API
$api_token = bin2hex(random_bytes(64 / 2));
$api_token_hash = password_hash($api_token, PASSWORD_BCRYPT, ["cost" => 12]);
$api_token_expiration_timestamp = strtotime('+1 year');
$query = "INSERT INTO system_api_tokens (api_token_uuid, user_uuid, api_token, api_token_expiration_timestamp, api_token_created_timestamp) VALUES (UUID(), ?, ?, ?, ?)";
$api_token_name = $this->data['api_token_name'] ?? null;
$query = "INSERT INTO system_api_tokens (api_token_uuid, user_uuid, api_token, api_token_name, api_token_expiration_timestamp, api_token_created_timestamp) VALUES (UUID(), ?, ?, ?, ?, ?)";
$stmt = $this->prepareStatement($query);
$stmt->bind_param('ssii', $this->data['user_uuid'], $api_token_hash, $api_token_expiration_timestamp, time());
$created_timestamp = time();
$stmt->bind_param('sssii', $this->data['user_uuid'], $api_token_hash, $api_token_name, $api_token_expiration_timestamp, $created_timestamp);
$this->executeStatement($stmt);

View File

@@ -37,9 +37,14 @@ if ($API_apitoken->request_method === 'GET') {
# Creates a new API Token. First check if the uuid is correct and then check the permission
# After that create a new token, retrieve the newly created api_token and give a response.
$requiredFields = [
'user_uuid' => ['type' => 'uuid'],
'user_uuid' => ['type' => 'uuid']
];
$API_apitoken->validateData($requiredFields);
$optionalFields = [
'api_token_name' => ['type' => 'string']
];
$API_apitoken->validateData($requiredFields, $optionalFields);
# First retrieve the user_uuid from the post and lookup the user
require_once $_SERVER['DOCUMENT_ROOT'] . '/api/classes/API_users.php';
@@ -48,8 +53,6 @@ if ($API_apitoken->request_method === 'GET') {
$_GET['builder'] = [1 => ['where' => [0 => 'user_uuid', 1 => $API_apitoken->data['user_uuid']]]];
$user_data = $API_users->getUser()[0];
$API_apitoken->validateData($requiredFields);
if ($API_apitoken->getUserUuid() === $API_apitoken->data['user_uuid']) {
$API_apitoken->checkPermissions('user-apitoken-self', 'RW');
@@ -57,6 +60,7 @@ if ($API_apitoken->request_method === 'GET') {
if ($user_data['user_email'] === 'superuser') {
$API_apitoken->apiOutput(401, ['error' => 'You are not authorized to access this resource.']);
}
$API_apitoken->checkPermissions('user-apitoken-others', 'RW');
}