Files
panel/app/Http/Controllers/Admin/NodeAutoDeployController.php

63 lines
1.8 KiB
PHP
Raw Normal View History

2020-04-12 17:20:09 -07:00
<?php
2024-03-12 22:39:16 -04:00
namespace App\Http\Controllers\Admin;
2020-04-12 17:20:09 -07:00
use Illuminate\Http\Request;
2024-03-12 22:39:16 -04:00
use App\Models\Node;
use App\Models\ApiKey;
2020-04-12 17:20:09 -07:00
use Illuminate\Http\JsonResponse;
2024-03-12 22:39:16 -04:00
use App\Http\Controllers\Controller;
use App\Services\Api\KeyCreationService;
2020-04-12 17:20:09 -07:00
class NodeAutoDeployController extends Controller
{
/**
* NodeAutoDeployController constructor.
*/
public function __construct(
private KeyCreationService $keyCreationService
2020-04-12 17:20:09 -07:00
) {
}
/**
* Generates a new API key for the logged-in user with only permission to read
2020-04-12 17:20:09 -07:00
* nodes, and returns that as the deployment key for a node.
*
2024-03-12 22:39:16 -04:00
* @throws \App\Exceptions\Model\DataValidationException
2020-04-12 17:20:09 -07:00
*/
public function __invoke(Request $request, Node $node): JsonResponse
2020-04-12 17:20:09 -07:00
{
2024-03-16 20:00:31 -04:00
$keys = $request->user()->apiKeys()
->where('key_type', ApiKey::TYPE_APPLICATION)
->get();
/** @var ApiKey|null $key */
$key = $keys
2020-04-12 17:20:09 -07:00
->filter(function (ApiKey $key) {
foreach ($key->getAttributes() as $permission => $value) {
if ($permission === 'r_nodes' && $value === 1) {
return true;
}
}
return false;
})
->first();
// We couldn't find a key that exists for this user with only permission for
// reading nodes. Go ahead and create it now.
2021-01-23 12:33:34 -08:00
if (!$key) {
2020-04-12 17:20:09 -07:00
$key = $this->keyCreationService->setKeyType(ApiKey::TYPE_APPLICATION)->handle([
'user_id' => $request->user()->id,
'memo' => 'Automatically generated node deployment key.',
'allowed_ips' => [],
], ['r_nodes' => 1]);
}
return new JsonResponse([
2020-04-12 17:20:09 -07:00
'node' => $node->id,
2024-03-19 05:11:41 -04:00
'token' => $key->identifier . decrypt($key->token),
2020-04-12 17:20:09 -07:00
]);
}
}