trypost/app/Actions/ApiKey/CreateApiKey.php
Paulo Castellano 8689e54e55 refactor: restructure to Actions, subdomain routes (app/api), API tokens
- Extract business logic from controllers into Action classes:
  Post/, Workspace/, Hashtag/, Label/, Invite/, ApiKey/
- Create subdomain routing: app.trypost.test (Inertia dashboard),
  api.trypost.test (REST API with token auth)
- Add ApiToken model with tp_ prefix, token_lookup/hash auth
- Add AuthenticateApiToken middleware for API authentication
- Create Api controllers with JSON Resources for all entities
- Create App controllers that use Actions + Inertia responses
- Organize Form Requests into Api/ and App/ directories
- Add api_tokens migration
- Update all route names with app. prefix
- Update all tests to use new route names (684 passing)
2026-03-29 19:24:28 -03:00

34 lines
963 B
PHP

<?php
declare(strict_types=1);
namespace App\Actions\ApiKey;
use App\Models\ApiToken;
use App\Models\Workspace;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class CreateApiKey
{
/**
* @param array{name: string, expires_at?: string|null} $data
* @return array{token: ApiToken, plain_token: string}
*/
public static function execute(Workspace $workspace, array $data): array
{
$plainToken = 'tp_'.Str::random(48);
$apiToken = ApiToken::create([
'workspace_id' => $workspace->id,
'name' => data_get($data, 'name'),
'token_lookup' => substr($plainToken, 3, 16),
'token_hash' => Hash::make($plainToken),
'expires_at' => data_get($data, 'expires_at')
? now()->parse(data_get($data, 'expires_at'))->endOfDay()
: null,
]);
return ['token' => $apiToken, 'plain_token' => $plainToken];
}
}