CreateAdminUserCommand.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\User;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Hash;
  6. class CreateAdminUserCommand extends Command
  7. {
  8. protected $signature = 'user:create-admin
  9. {username=17689974321 : 登录手机号(与后台「手机号」一致,对应 users.username)}
  10. {password=123qwe#0 : 明文密码;含 # 时请用单引号包裹整个参数}';
  11. protected $description = '创建或更新管理员账号(role=admin,is_active=1),用于登录 /admin';
  12. public function handle(): int
  13. {
  14. $username = (string) $this->argument('username');
  15. $password = (string) $this->argument('password');
  16. if ($username === '') {
  17. $this->error('username 不能为空');
  18. return self::FAILURE;
  19. }
  20. $user = User::where('username', $username)->first();
  21. if (! $user) {
  22. $user = new User;
  23. $user->username = $username;
  24. $user->full_name = '系统管理员';
  25. $user->email = null;
  26. }
  27. $user->password_hash = Hash::make($password);
  28. $user->role = 'admin';
  29. $user->is_active = true;
  30. if ($user->full_name === '' || $user->full_name === null) {
  31. $user->full_name = '系统管理员';
  32. }
  33. $user->save();
  34. $this->info("已就绪:username={$user->username} role=admin 登录 /admin 使用手机号+密码");
  35. return self::SUCCESS;
  36. }
  37. }