diff --git a/src/Auth/Command/CreateAdminCommand.php b/src/Auth/Command/CreateAdminCommand.php new file mode 100644 index 00000000..38bd3b45 --- /dev/null +++ b/src/Auth/Command/CreateAdminCommand.php @@ -0,0 +1,76 @@ +addArgument('mobile', InputArgument::OPTIONAL, 'Mobile number, e.g. 09120671756') + ->addArgument('password', InputArgument::OPTIONAL, 'Plain password (will be hashed)'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $mobile = $input->getArgument('mobile') ?: $io->ask('Mobile number'); + $password = $input->getArgument('password') ?: $io->askHidden('Password'); + + if (!$mobile || !$password) { + $io->error('Mobile and password are required.'); + return Command::INVALID; + } + + $repo = $this->em->getRepository(User::class); + $user = $repo->findOneBy(['mobileNumber' => $mobile]); + $existed = $user !== null; + + if (!$existed) { + $user = new User($mobile); + } + + $roles = $user->getRoles(); + if (!in_array('ROLE_ADMIN', $roles, true)) { + $roles[] = 'ROLE_ADMIN'; + $user->setRoles($roles); + } + $user->setPasswordHash($this->hasher->hashPassword($user, $password)); + $user->setStatus(1); + + $this->em->persist($user); + $this->em->flush(); + + $io->success(sprintf( + '%s admin %s (uuid=%s, roles=%s)', + $existed ? 'Promoted' : 'Created', + $mobile, + $user->getUuid(), + implode(',', $user->getRoles()), + )); + + return Command::SUCCESS; + } +}