You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Console\Commands;
use App\Models\AdminUser;
use Illuminate\Console\Command;
class ResetAdminPasswordCommand extends Command
{
protected $signature = 'admin:password
{username : 后台管理员用户名}
{--password= : 新密码;不传时使用隐藏交互输入}
{--yes : 跳过确认提示}';
protected $description = '修改后台管理员登录密码';
public function handle(): int
{
$username = trim((string) $this->argument('username'));
if ($username === '') {
$this->error('用户名不能为空。');
return self::FAILURE;
}
$admin = AdminUser::query()->where('username', $username)->first();
if (! $admin) {
$this->error("未找到后台管理员账号:{$username}");
return self::FAILURE;
}
$password = $this->resolvePassword();
if ($password === null) {
return self::FAILURE;
}
if (! $this->option('yes')) {
$name = $admin->name !== '' ? "{$admin->name}" : '';
if (! $this->confirm("确认修改后台管理员 {$admin->username}{$name} 的密码?", false)) {
$this->warn('已取消修改。');
return self::FAILURE;
}
}
$admin->forceFill([
'password_hash' => $password,
])->save();
$this->info("后台管理员 {$admin->username} 的密码已更新。");
return self::SUCCESS;
}
private function resolvePassword(): ?string
{
$password = $this->option('password');
if ($password !== null) {
$password = (string) $password;
return $this->validatePassword($password) ? $password : null;
}
$password = (string) $this->secret('请输入新密码');
if (! $this->validatePassword($password)) {
return null;
}
$confirmation = (string) $this->secret('请再次输入新密码');
if ($password !== $confirmation) {
$this->error('两次输入的密码不一致。');
return null;
}
return $password;
}
private function validatePassword(string $password): bool
{
if (mb_strlen($password) < 6) {
$this->error('密码长度不能少于 6 个字符。');
return false;
}
if (mb_strlen($password) > 255) {
$this->error('密码长度不能超过 255 个字符。');
return false;
}
return true;
}
}