8000 [SecurityBundle] UserPasswordEncoderCommand: Improve & simplify the command usage by ogizanagi · Pull Request #14032 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[SecurityBundle] UserPasswordEncoderCommand: Improve & simplify the command usage #14032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[SecurityBundle] UserPasswordEncoderCommand: Tweak output, complying …
…with console style guide
  • Loading branch information
ogizanagi committed Apr 6, 2015
commit b9374cc54f80c06aec5050293de5fa02d9eb4fe2
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@
namespace Symfony\Bundle\SecurityBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

/**
Expand Down Expand Up @@ -85,34 +84,39 @@ protected function configure()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->writeIntroduction($output);
$output = new SymfonyStyle($input, $output);

$input->isInteractive() ? $output->title('Symfony Password Encoder Utility') : $output->newLine();

$password = $input->getArgument('password');
$userClass = $input->getArgument('user-class');
$emptySalt = $input->getOption('empty-salt');

$helper = $this->getHelper('question');
$encoder = $this->getContainer()->get('security.encoder_factory')->getEncoder($userClass);
$bcryptWithoutEmptySalt = !$emptySalt && $encoder instanceof BCryptPasswordEncoder;

if ($bcryptWithoutEmptySalt) {
$emptySalt = true;
}

if (!$password) {
if (!$input->isInteractive()) {
throw new \Exception('The password must not be empty.');
$output->error('The password must not be empty.');

return 1;
}
$passwordQuestion = $this->createPasswordQuestion($input, $output);
$password = $helper->ask($input, $output, $passwordQuestion);
}

$encoder = $this->getContainer()->get('security.encoder_factory')->getEncoder($userClass);

if (!$emptySalt && $encoder instanceof BCryptPasswordEncoder) {
$output->writeln('<fg=yellow>! [NOTE] Bcrypt encoder detected. The command will assume the salt should be generated by the encoder.</>'.PHP_EOL);
$emptySalt = true;
$password = $output->askQuestion($passwordQuestion);
}

$salt = null;

if ($input->isInteractive() && !$emptySalt) {
$emptySalt = true;
if ($helper->ask($input, $output, $this->createSaltQuestion($output))) {

$output->note('The command will take care of generating a salt for you. Be aware that some encoders advise to let them generate their own salt. If you\'re using one of those encoders, please answer \'no\' to the question below. '.PHP_EOL.'Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.');

if ($output->confirm('Confirm salt generation ?')) {
$salt = $this->generateSalt();
$emptySalt = false;
}
Expand All @@ -122,98 +126,40 @@ protected function execute(InputInterface $input, OutputInterface $output)

$encodedPassword = $encoder->encodePassword($password, $salt);

$this->writeResult($output);

$table = new Table($output);
$table
->setHeaders(array('Key', 'Value'))
->addRow(array('Encoder used', get_class($encoder)))
->addRow(array('Encoded password', $encodedPassword));
$rows = array(
array('Encoder used', get_class($encoder)),
array('Encoded password', $encodedPassword),
);
if (!$emptySalt) {
$rows[] = array('Generated salt', $salt);
}
$output->table(array('Key', 'Value'), $rows);

if ($emptySalt) {
$table->render();
} else {
$table->addRow(array('Generated salt', $salt));
$table->render();
$output->writeln(sprintf("<comment>Make sure that your salt storage field fits this salt length: %s chars.</comment>\n", strlen($salt)));
if (!$emptySalt) {
$output->note(sprintf('Make sure that your salt storage field fits the salt length: %s chars', strlen($salt)));
} elseif ($bcryptWithoutEmptySalt) {
$output->note('Bcrypt encoder used: the encoder generated its own built-in salt.');
}

$output->success('Password encoding succeeded');
}

/**
* Create the password question to ask the user for the password to be encoded.
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return Question
*/
private function createPasswordQuestion(InputInterface $input, OutputInterface $output)
private function createPasswordQuestion()
{
$passwordQuestion = new Question("\n > <question>Type in your password to be encoded:</question> ");
$passwordQuestion = new Question('Type in your password to be encoded');

$passwordQuestion->setValidator(function ($value) {
return $passwordQuestion->setValidator(function ($value) {
if ('' === trim($value)) {
throw new \Exception('The password must not be empty.');
}

return $value;
});
$passwordQuestion->setHidden(true);
$passwordQuestion->setMaxAttempts(20);

return $passwordQuestion;
}

/**
* Create the question that asks for the salt generation confirmation.
*
* @param OutputInterface $output
*
* @return ConfirmationQuestion
*/
private function createSaltQuestion(OutputInterface $output)
{
$output->writeln(array(
'<fg=yellow>! [NOTE] The command will take care of generating a salt for you.',
'! Be aware that some encoders advise to let them generate their own salt.',
'! If you\'re using one of those encoders, please answer \'no\' to the question below.',
'! Provide the \'empty-salt\' option in order to let the encoder handle the generation itself.</>'.PHP_EOL,
));

return new ConfirmationQuestion('Confirm salt generation ? <info> (yes/no)</info> [<comment>yes</comment>]:', true);
}

private function writeIntroduction(OutputInterface $output)
{
$output->writeln(array(
'',
$this->getHelperSet()->get('formatter')->formatBlock(
'Symfony Password Encoder Utility',
'bg=blue;fg=white',
true
),
'',
));

$output->writeln(array(
'',
'This command encodes any password you want according to the configuration you',
'made in your configuration file containing the <comment>security.encoders</comment> key.',
'',
));
}

private function writeResult(OutputInterface $output)
{
$output->writeln(array(
'',
$this->getHelperSet()->get('formatter')->formatBlock(
'✔ Password encoding succeeded',
'bg=green;fg=white',
true
),
'',
));
})->setHidden(true)->setMaxAttempts(20);
}

private function generateSalt()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,12 @@ public function testEncodePasswordEmptySalt()

public function testEncodeNoPasswordNoInteraction()
{
$this->setExpectedException('\Exception', 'The password must not be empty.');

$this->passwordEncoderCommandTester->execute(array(
$statusCode = $this->passwordEncoderCommandTester->execute(array(
'command' => 'security:encode-password',
), array('interactive' => false));

$this->assertContains('[ERROR] The password must not be empty.', $this->passwordEncoderCommandTester->getDisplay());
$this->assertEquals($statusCode, 1);
}

public function testEncodePasswordBcrypt()
Expand All @@ -60,7 +61,7 @@ public function testEncodePasswordBcrypt()
$this->assertContains('Password encoding succeeded', $output);

$encoder = new BCryptPasswordEncoder(17);
preg_match('#\| Encoded password \| ([a-zA-Z0-9+\/$.]+={0,2})\s+\|#', $output, $matches);
preg_match('# Encoded password\s{1,}([\w+\/$.]+={0,2})\s+#', $output, $matches);
$hash = $matches[1];
$this->assertTrue($encoder->isPasswordValid($hash, 'password', null));
}
Expand All @@ -77,9 +78,9 @@ public function testEncodePasswordPbkdf2()
$this->assertContains('Password encoding succeeded', $output);

$encoder = new Pbkdf2PasswordEncoder('sha512', true, 1000);
preg_match('#\| Encoded password \| ([a-zA-Z0-9+\/$.]+={0,2})\s+\|#', $output, $matches);
preg_match('# Encoded password\s{1,}([\w+\/]+={0,2})\s+#', $output, $matches);
$hash = $matches[1];
preg_match('#\| Generated salt \| ([a-zA-Z0-9+\/]+={0,2})\s+\|#', $output, $matches);
preg_match('# Generated salt\s{1,}([\w+\/]+={0,2})\s+#', $output, $matches);
$salt = $matches[1];
$this->assertTrue($encoder->isPasswordValid($hash, 'password', $salt));
}
Expand All @@ -94,8 +95,8 @@ public function testEncodePasswordOutput()
);

$this->assertContains('Password encoding succeeded', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains('| Encoded password | p@ssw0rd', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains('| Generated salt |', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains(' Encoded password p@ssw0rd', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains(' Generated salt ', $this->passwordEncoderCommandTester->getDisplay());
}

public function testEncodePasswordEmptySaltOutput()
Expand All @@ -109,8 +110,8 @@ public function testEncodePasswordEmptySaltOutput()
);

$this->assertContains('Password encoding succeeded', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains('| Encoded password | p@ssw0rd', $this->passwordEncoderCommandTester->getDisplay());
$this->assertNotContains('| Generated salt |', $this->passwordEncoderCommandTester->getDisplay());
$this->assertContains(' Encoded password p@ssw0rd', $this->passwordEncoderCommandTester->getDisplay());
$this->assertNotContains(' Generated salt ', $this->passwordEncoderCommandTester->getDisplay());
}

public function testEncodePasswordBcryptOutput()
Expand All @@ -123,7 +124,7 @@ public function testEncodePasswordBcryptOutput()
)
);

$this->assertNotContains('| Generated salt |', $this->passwordEncoderCommandTester->getDisplay());
$this->assertNotContains(' Generated salt ', $this->passwordEncoderCommandTester->getDisplay());
}

public function testEncodePasswordNoConfigForGivenUserClass()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@


Symfony Password Encoder Utility

Symfony Password Encoder Utility
================================

------------------ ------------------------------------------------------------------
Key Value
------------------ ------------------------------------------------------------------
Encoder used Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder
Encoded password password
------------------ ------------------------------------------------------------------

This command encodes any password you want according to the configuration you
made in your configuration file containing the security.encoders key.
[OK] Password encoding succeeded



✔ Password encoding succeeded


+------------------+------------------------------------------------------------------+
| Key | Value |
+------------------+------------------------------------------------------------------+
| Encoder used | Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder |
| Encoded password | password |
+------------------+------------------------------------------------------------------+
0