diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 5073e29..a17fa6e 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -1,4 +1,6 @@ security: + role_hierarchy: + ROLE_ADMIN: ROLE_USER # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords password_hashers: Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' @@ -42,6 +44,7 @@ security: - { path: ^/_profiler, roles: PUBLIC_ACCESS } - { path: ^/_wdt, roles: PUBLIC_ACCESS } - { path: ^/, roles: ROLE_USER } + when@test: security: password_hashers: diff --git a/k8s/deployment.yaml b/k8s/deployment.yaml index a23b2bf..f81285c 100644 --- a/k8s/deployment.yaml +++ b/k8s/deployment.yaml @@ -24,7 +24,7 @@ spec: containers: - name: symfony - image: symfony-k3s:dev-2 + image: symfony-k3s:dev-5 imagePullPolicy: Never ports: diff --git a/src/Command/CreateUserCommand.php b/src/Command/CreateUserCommand.php new file mode 100644 index 0000000..ccd9ed0 --- /dev/null +++ b/src/Command/CreateUserCommand.php @@ -0,0 +1,103 @@ +addArgument( + 'email', + InputArgument::REQUIRED, + 'Email address' + ) + ->addArgument( + 'password', + InputArgument::REQUIRED, + 'Plain-text password' + ) + ->addOption( + 'admin', + null, + InputOption::VALUE_NONE, + 'Assign ROLE_ADMIN' + ); + } + + protected function execute( + InputInterface $input, + OutputInterface $output, + ): int { + $email = strtolower(trim( + (string) $input->getArgument('email') + )); + + $plainPassword = (string) $input->getArgument('password'); + + $existingUser = $this->entityManager + ->getRepository(User::class) + ->findOneBy(['email' => $email]); + + if ($existingUser !== null) { + $output->writeln( + sprintf( + 'User "%s" already exists.', + $email + ) + ); + + return Command::FAILURE; + } + + $user = new User(); + $user->setEmail($email); + $user->setRoles( + $input->getOption('admin') + ? ['ROLE_ADMIN'] + : ['ROLE_USER'] + ); + + $user->setPassword( + $this->passwordHasher->hashPassword( + $user, + $plainPassword + ) + ); + + $this->entityManager->persist($user); + $this->entityManager->flush(); + + $output->writeln( + sprintf( + 'User "%s" created successfully.', + $email + ) + ); + + return Command::SUCCESS; + } +}