Files
CKB-Interface/application/command/GenerateUserApiKeyCommand.php
2026-03-24 10:39:16 +08:00

112 lines
3.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\Db;
use app\common\service\UserApiKeyService;
/**
* 批量为 ck_users 表中还没有 apiKey 的用户生成专属 Key
*
* 用法:
* php think user:generate-api-key # 只处理没有 apiKey 的用户
* php think user:generate-api-key --force # 强制覆盖所有用户的 apiKey危险
* php think user:generate-api-key --dry-run # 预览模式,不写库
*/
class GenerateUserApiKeyCommand extends Command
{
protected function configure()
{
$this->setName('user:generate-api-key')
->setDescription('批量为 ck_users 用户生成对外 API Key')
->addOption('force', 'f', Option::VALUE_NONE, '强制覆盖所有用户(包括已有 apiKey 的用户),危险!')
->addOption('dry-run', null, Option::VALUE_NONE, '预览模式,不实际写入数据库');
}
protected function execute(Input $input, Output $output)
{
$force = (bool)$input->getOption('force');
$dryRun = (bool)$input->getOption('dry-run');
$output->writeln('<info>========================================</info>');
$output->writeln('<info> 批量生成用户 API Key</info>');
$output->writeln('<info>========================================</info>');
if ($dryRun) {
$output->writeln('<comment>[预览模式] 不会实际写入数据库</comment>');
}
if ($force) {
$output->writeln('<comment>[FORCE] 将覆盖已有 apiKey 的用户</comment>');
}
$output->writeln('');
// 查询目标用户
$query = Db::name('users')
->where('deleteTime', 0)
->field('id, account, phone, apiKey');
if (!$force) {
// 默认只处理 apiKey 为空或 NULL 的记录
$query->where(function ($q) {
$q->where('apiKey', null)
->whereOr('apiKey', '');
});
}
$users = $query->select();
$total = count($users);
$success = 0;
$skip = 0;
$output->writeln("共找到 <info>{$total}</info> 个需要处理的用户");
$output->writeln('');
if ($total === 0) {
$output->writeln('<info>所有用户均已有 API Key无需处理。</info>');
return true;
}
foreach ($users as $user) {
$uid = (int)$user['id'];
$label = "用户 #{$uid} ({$user['account']}/{$user['phone']})";
try {
if ($dryRun) {
$output->writeln("<comment>[预览] 将为 {$label} 生成 apiKey</comment>");
$success++;
continue;
}
if ($force) {
$apiKey = UserApiKeyService::forceGenerate($uid);
} else {
$apiKey = UserApiKeyService::bindOrGet($uid);
}
$output->writeln("<info>√ {$label} => {$apiKey}</info>");
$success++;
} catch (\Exception $e) {
$output->writeln("<error>✗ {$label} 失败:{$e->getMessage()}</error>");
$skip++;
}
}
$output->writeln('');
$output->writeln('<info>========================================</info>');
$output->writeln("<info> 完成:成功 {$success} 个,跳过/失败 {$skip} 个</info>");
$output->writeln('<info>========================================</info>');
if ($dryRun) {
$output->writeln('<comment>预览模式:未实际写入任何数据</comment>');
}
return true;
}
}