GenerateApiKeyCommand.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace App\Module\OpenAPI\Commands;
  3. use App\Module\OpenAPI\Models\OpenApiApp;
  4. use App\Module\OpenAPI\Models\OpenApiKey;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Str;
  7. /**
  8. * 生成API密钥命令
  9. */
  10. class GenerateApiKeyCommand extends Command
  11. {
  12. /**
  13. * 命令签名
  14. *
  15. * @var string
  16. */
  17. protected $signature = 'openapi:generate-key
  18. {app_id : 应用ID}
  19. {--name= : 密钥名称}
  20. {--description= : 密钥描述}
  21. {--scopes=* : 权限范围}
  22. {--expires= : 过期时间(天数)}';
  23. /**
  24. * 命令描述
  25. *
  26. * @var string
  27. */
  28. protected $description = '为指定应用生成新的API密钥';
  29. /**
  30. * 执行命令
  31. *
  32. * @return int
  33. */
  34. public function handle()
  35. {
  36. $appId = $this->argument('app_id');
  37. // 验证应用是否存在
  38. $app = OpenApiApp::where('app_id', $appId)->first();
  39. if (!$app) {
  40. $this->error("应用 {$appId} 不存在");
  41. return 1;
  42. }
  43. // 检查应用状态
  44. if (!in_array($app->status, ['ACTIVE', 'APPROVED'])) {
  45. $this->error("应用 {$appId} 状态不允许生成密钥,当前状态: {$app->status}");
  46. return 1;
  47. }
  48. // 获取参数
  49. $name = $this->option('name') ?: 'Generated Key';
  50. $description = $this->option('description') ?: '';
  51. $scopes = $this->option('scopes') ?: $app->scopes;
  52. $expiresDays = $this->option('expires');
  53. // 计算过期时间
  54. $expiresAt = null;
  55. if ($expiresDays) {
  56. $expiresAt = now()->addDays((int)$expiresDays);
  57. }
  58. // 生成密钥
  59. $keyId = 'ak_' . Str::random(32);
  60. $keySecret = 'sk_' . Str::random(64);
  61. $apiKey = OpenApiKey::create([
  62. 'app_id' => $appId,
  63. 'key_id' => $keyId,
  64. 'key_secret' => hash('sha256', $keySecret), // 加密存储
  65. 'name' => $name,
  66. 'description' => $description,
  67. 'scopes' => $scopes,
  68. 'status' => 'ACTIVE',
  69. 'expires_at' => $expiresAt,
  70. ]);
  71. // 显示结果
  72. $this->info('API密钥生成成功!');
  73. $this->line('');
  74. $this->line("应用ID: {$appId}");
  75. $this->line("应用名称: {$app->name}");
  76. $this->line("密钥ID: {$keyId}");
  77. $this->line("密钥Secret: {$keySecret}");
  78. $this->line("密钥名称: {$name}");
  79. $this->line("权限范围: " . implode(', ', $scopes));
  80. if ($expiresAt) {
  81. $this->line("过期时间: {$expiresAt->format('Y-m-d H:i:s')}");
  82. } else {
  83. $this->line("过期时间: 永不过期");
  84. }
  85. $this->line('');
  86. $this->warn('请妥善保存密钥信息,系统不会再次显示完整的密钥Secret!');
  87. return 0;
  88. }
  89. }