How to access the user Token in an injected service to reencode passwords?

倖福魔咒の 提交于 2019-12-01 22:42:42

In your services, you can only access what dependencies you've injected.

So, to access the current user object, you need to pass it as argument:

service:

club.password_rehash:
    class: AppBundle\Service\PasswordRehash
    arguments: [ "@security.token_storage" ]

Constructor:

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class HubAuthenticator extends \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder implements PasswordEncoderInterface
{
    private $storage;

    function __construct($cost = 13, TokenStorageInterface $storage)
    {
        parent::__construct($cost);

        $this->storage = $storage;
        // Now you can use:
        // $user = $this->storage->getToken()->getUser();
    }
}

Then, to access the second service, same way, inject it.

Add it to the service arguments:

club.password_rehash:
    class: AppBundle\Service\PasswordRehash
    arguments: [ "@security.token_storage", "@club.password_rehash" ]

Add it to your constructor:

private $storage;
private $passwordRehash

function __construct($cost = 13, TokenStorageInterface $storage, PasswordRehash $passwordRehash)
{
    parent::__construct($cost);

    $this->storage = $storage;
    $this->passwordRehash = $passwordRehash;
    // Now you can use:
    // $this->passwordRehash->rehash(...);
}

Hope this helps you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!