| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
- namespace App\Module\OpenAPI\Commands;
- use App\Module\OpenAPI\Models\OpenApiApp;
- use App\Module\OpenAPI\Models\OpenApiKey;
- use Illuminate\Console\Command;
- use Illuminate\Support\Str;
- /**
- * 生成API密钥命令
- */
- class GenerateApiKeyCommand extends Command
- {
- /**
- * 命令签名
- *
- * @var string
- */
- protected $signature = 'openapi:generate-key
- {app_id : 应用ID}
- {--name= : 密钥名称}
- {--description= : 密钥描述}
- {--scopes=* : 权限范围}
- {--expires= : 过期时间(天数)}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '为指定应用生成新的API密钥';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle()
- {
- $appId = $this->argument('app_id');
-
- // 验证应用是否存在
- $app = OpenApiApp::where('app_id', $appId)->first();
- if (!$app) {
- $this->error("应用 {$appId} 不存在");
- return 1;
- }
- // 检查应用状态
- if (!in_array($app->status, ['ACTIVE', 'APPROVED'])) {
- $this->error("应用 {$appId} 状态不允许生成密钥,当前状态: {$app->status}");
- return 1;
- }
- // 获取参数
- $name = $this->option('name') ?: 'Generated Key';
- $description = $this->option('description') ?: '';
- $scopes = $this->option('scopes') ?: $app->scopes;
- $expiresDays = $this->option('expires');
- // 计算过期时间
- $expiresAt = null;
- if ($expiresDays) {
- $expiresAt = now()->addDays((int)$expiresDays);
- }
- // 生成密钥
- $keyId = 'ak_' . Str::random(32);
- $keySecret = 'sk_' . Str::random(64);
- $apiKey = OpenApiKey::create([
- 'app_id' => $appId,
- 'key_id' => $keyId,
- 'key_secret' => hash('sha256', $keySecret), // 加密存储
- 'name' => $name,
- 'description' => $description,
- 'scopes' => $scopes,
- 'status' => 'ACTIVE',
- 'expires_at' => $expiresAt,
- ]);
- // 显示结果
- $this->info('API密钥生成成功!');
- $this->line('');
- $this->line("应用ID: {$appId}");
- $this->line("应用名称: {$app->name}");
- $this->line("密钥ID: {$keyId}");
- $this->line("密钥Secret: {$keySecret}");
- $this->line("密钥名称: {$name}");
- $this->line("权限范围: " . implode(', ', $scopes));
-
- if ($expiresAt) {
- $this->line("过期时间: {$expiresAt->format('Y-m-d H:i:s')}");
- } else {
- $this->line("过期时间: 永不过期");
- }
- $this->line('');
- $this->warn('请妥善保存密钥信息,系统不会再次显示完整的密钥Secret!');
- return 0;
- }
- }
|