Skip to content

Commit

Permalink
feature Sylius#10084 Password hashing - update encoder on login (pamil)
Browse files Browse the repository at this point in the history
This PR was merged into the 1.4-dev branch.

Discussion
----------

| Q               | A
| --------------- | -----
| Branch?         | 1.4
| Bug fix?        | no
| New feature?    | yes
| BC breaks?      | no
| Deprecations?   | no
| Related tickets | closes Sylius#9560, related to Sylius#10080
| License         | MIT

TODO:
 - [x] Functional test at the application level which updates the encoder and password of logged in user

<!--
 - Bug fixes must be submitted against the 1.2 or 1.3 branch (the lowest possible)
 - Features and deprecations must be submitted against the master branch
 - Make sure that the correct base branch is set
-->


Commits
-------

d05d8aa Specify an listener to update the encoded password on login
e58b202 Register the listener updating users' encoder
b79be03 Add encoder name to serialised user data
93d7aed Add functional test for update password encoder listener
722ba00 Set "argon2i" as the default encoder
f2e6896 Setup seamless change to argon2i
d02581b Make test compatibile with Symfony 3.4
62eb4ab Mock what you own in encoder listener spec
  • Loading branch information
pamil committed Jan 11, 2019
2 parents 72cd3e7 + 62eb4ab commit 6667183
Show file tree
Hide file tree
Showing 12 changed files with 517 additions and 20 deletions.
3 changes: 0 additions & 3 deletions config/packages/_sylius.yaml
Expand Up @@ -12,6 +12,3 @@ parameters:
sylius_shop:
product_grid:
include_all_descendants: true

sylius_user:
encoder: argon2i
3 changes: 1 addition & 2 deletions config/packages/security.yaml
Expand Up @@ -10,8 +10,7 @@ security:
sylius_shop_user_provider:
id: sylius.shop_user_provider.email_or_name_based
encoders:
Sylius\Component\User\Model\UserInterface: sha512
argon2i: argon2i
Sylius\Component\User\Model\UserInterface: argon2i
firewalls:
admin:
switch_user: true
Expand Down
3 changes: 3 additions & 0 deletions config/packages/test/security.yaml
@@ -0,0 +1,3 @@
security:
encoders:
sha512: sha512
Expand Up @@ -14,6 +14,7 @@
namespace Sylius\Bundle\UserBundle\DependencyInjection;

use Sylius\Bundle\ResourceBundle\DependencyInjection\Extension\AbstractResourceExtension;
use Sylius\Bundle\UserBundle\EventListener\UpdateUserEncoderListener;
use Sylius\Bundle\UserBundle\EventListener\UserDeleteListener;
use Sylius\Bundle\UserBundle\EventListener\UserLastLoginSubscriber;
use Sylius\Bundle\UserBundle\EventListener\UserReloaderListener;
Expand All @@ -32,6 +33,7 @@
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Security\Http\SecurityEvents;

final class SyliusUserExtension extends AbstractResourceExtension
{
Expand All @@ -50,7 +52,7 @@ public function load(array $config, ContainerBuilder $container): void
$loader->load('services.xml');

$this->createServices($config['resources'], $container);
$this->createFactories($config['encoder'], $config['resources'], $container);
$this->loadEncodersAwareServices($config['encoder'], $config['resources'], $container);
}

private function resolveResources(array $resources, ContainerBuilder $container): array
Expand Down Expand Up @@ -82,7 +84,7 @@ private function createServices(array $resources, ContainerBuilder $container):
}
}

private function createFactories(?string $globalEncoder, array $resources, ContainerBuilder $container): void
private function loadEncodersAwareServices(?string $globalEncoder, array $resources, ContainerBuilder $container): void
{
foreach ($resources as $userType => $config) {
$encoder = $config['user']['encoder'] ?? $globalEncoder;
Expand All @@ -91,18 +93,8 @@ private function createFactories(?string $globalEncoder, array $resources, Conta
continue;
}

$factoryServiceId = sprintf('sylius.factory.%s_user', $userType);

$factoryDefinition = new Definition(
UserWithEncoderFactory::class,
[
$container->getDefinition($factoryServiceId),
$encoder,
]
);
$factoryDefinition->setPublic(true);

$container->setDefinition($factoryServiceId, $factoryDefinition);
$this->overwriteResourceFactoryWithEncoderAwareFactory($container, $userType, $encoder);
$this->registerUpdateUserEncoderListener($container, $userType, $encoder, $config);
}
}

Expand Down Expand Up @@ -252,4 +244,37 @@ private function createProviders(string $userType, string $userModel, ContainerB
$emailOrNameBasedProviderDefinition->setClass(UsernameOrEmailProvider::class);
$container->setDefinition($providerEmailOrNameBasedServiceId, $emailOrNameBasedProviderDefinition);
}

private function overwriteResourceFactoryWithEncoderAwareFactory(ContainerBuilder $container, string $userType, string $encoder): void
{
$factoryServiceId = sprintf('sylius.factory.%s_user', $userType);

$factoryDefinition = new Definition(
UserWithEncoderFactory::class,
[
$container->getDefinition($factoryServiceId),
$encoder,
]
);
$factoryDefinition->setPublic(true);

$container->setDefinition($factoryServiceId, $factoryDefinition);
}

private function registerUpdateUserEncoderListener(ContainerBuilder $container, string $userType, string $encoder, array $resourceConfig): void
{
$updateUserEncoderListenerDefinition = new Definition(UpdateUserEncoderListener::class, [
new Reference(sprintf('sylius.manager.%s_user', $userType)),
$encoder,
$resourceConfig['user']['classes']['model'],
$resourceConfig['user']['classes']['interface'],
'_password',
]);
$updateUserEncoderListenerDefinition->addTag('kernel.event_listener', ['event' => SecurityEvents::INTERACTIVE_LOGIN]);

$container->setDefinition(
sprintf('sylius.%s_user.listener.update_user_encoder', $userType),
$updateUserEncoderListenerDefinition
);
}
}
@@ -0,0 +1,80 @@
<?php

/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace Sylius\Bundle\UserBundle\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Component\User\Model\UserInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

final class UpdateUserEncoderListener
{
/** @var ObjectManager */
private $objectManager;

/** @var string */
private $recommendedEncoderName;

/** @var string */
private $className;

/** @var string */
private $interfaceName;

/** @var string */
private $passwordParameter;

public function __construct(
ObjectManager $objectManager,
string $recommendedEncoderName,
string $className,
string $interfaceName,
string $passwordParameter
) {
$this->objectManager = $objectManager;
$this->recommendedEncoderName = $recommendedEncoderName;
$this->className = $className;
$this->interfaceName = $interfaceName;
$this->passwordParameter = $passwordParameter;
}

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
{
$user = $event->getAuthenticationToken()->getUser();

if (!$user instanceof UserInterface) {
return;
}

if (!$user instanceof $this->className || !$user instanceof $this->interfaceName) {
return;
}

if ($user->getEncoderName() === $this->recommendedEncoderName) {
return;
}

$request = $event->getRequest();

$plainPassword = $request->request->get($this->passwordParameter);
if (null === $plainPassword || '' === $plainPassword) {
return;
}

$user->setEncoderName($this->recommendedEncoderName);
$user->setPlainPassword($plainPassword);

$this->objectManager->persist($user);
$this->objectManager->flush();
}
}
7 changes: 7 additions & 0 deletions src/Sylius/Bundle/UserBundle/Resources/config/app/config.yml
@@ -1,6 +1,13 @@
# This file is part of the Sylius package.
# (c) Paweł Jędrzejewski

security:
encoders:
argon2i: argon2i

sylius_user:
encoder: argon2i

jms_serializer:
metadata:
directories:
Expand Down
Expand Up @@ -7,8 +7,11 @@
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
use PHPUnit\Framework\Assert;
use Sylius\Bundle\UserBundle\DependencyInjection\SyliusUserExtension;
use Sylius\Bundle\UserBundle\EventListener\UpdateUserEncoderListener;
use Sylius\Bundle\UserBundle\Factory\UserWithEncoderFactory;
use Sylius\Component\Resource\Factory\Factory;
use Sylius\Component\User\Model\User;
use Sylius\Component\User\Model\UserInterface;

final class SyliusUserExtensionTest extends AbstractExtensionTestCase
{
Expand Down Expand Up @@ -85,6 +88,42 @@ public function it_decorates_user_factory_using_the_most_specific_encoder_config
Assert::assertSame('evenmorecustomencoder', $factoryDefinition->getArgument(1));
}

/** @test */
public function it_creates_a_update_user_encoder_listener_for_each_user_type(): void
{
$this->load([
'encoder' => 'customencoder',
'resources' => [
'admin' => [
'user' => [
'encoder' => 'evenmorecustomencoder',
'classes' => [
'model' => 'AdminUserClass',
'interface' => 'AdminUserInterface',
],
],
],
'shop' => [],
],
]);

$adminUserListenerDefinition = $this->container->getDefinition('sylius.admin_user.listener.update_user_encoder');

Assert::assertSame(UpdateUserEncoderListener::class, $adminUserListenerDefinition->getClass());
Assert::assertSame('evenmorecustomencoder', $adminUserListenerDefinition->getArgument(1));
Assert::assertSame('AdminUserClass', $adminUserListenerDefinition->getArgument(2));
Assert::assertSame('AdminUserInterface', $adminUserListenerDefinition->getArgument(3));
Assert::assertSame('_password', $adminUserListenerDefinition->getArgument(4));

$shopUserListenerDefinition = $this->container->getDefinition('sylius.shop_user.listener.update_user_encoder');

Assert::assertSame(UpdateUserEncoderListener::class, $shopUserListenerDefinition->getClass());
Assert::assertSame('customencoder', $shopUserListenerDefinition->getArgument(1));
Assert::assertSame(User::class, $shopUserListenerDefinition->getArgument(2));
Assert::assertSame(UserInterface::class, $shopUserListenerDefinition->getArgument(3));
Assert::assertSame('_password', $shopUserListenerDefinition->getArgument(4));
}

protected function getContainerExtensions(): iterable
{
return [
Expand Down

0 comments on commit 6667183

Please sign in to comment.