Symfony2 FOS 修改密码功能

有时候我们需要自己定义修改密码界面和功能,但是我们又不知道系统的加密规则,那么,我们可以安装FOS自带修改密码功能,但是不知为何修改密码路由总是增加失败,又或者要自己重写,怎么办呢?


(1)我们可以调用FOS的修改密码函数,如下:

$manipulator = $this->container->get('fos_user.util.user_manipulator');
$manipulator->changePassword($user->getUsername(), $form->getData()['plain_password']);

该service所在类:

FOS\UserBundle\Util\UserManipulator
/**
 * Changes the password for the given user.
 *
 * @param string $username
 * @param string $password
 */
public function changePassword($username, $password)
{
    $user = $this->userManager->findUserByUsername($username);
       
    if (!$user) {
        throw new \InvalidArgumentException(sprintf('User identified by "%s" username does not exist.', $username));
    }
    $user->setPlainPassword($password);
    $this->userManager->updateUser($user);
}

注:$password为更改后的密码的“明文”


(2)修改密码时我们需要校验密码是否正确,我们不知道加密规则,同样我们也可以调用Symfony的校验函数,如下:

$encoder = $this->container->get('security.password_encoder');
$encoder->isPasswordValid($this->getUser(),$form->getData()['old_password']);

该service所在类:

Symfony\Component\Security\Core\Encoder\UserPasswordEncoder
/**
 * {@inheritdoc}
 */
public function isPasswordValid(UserInterface $user, $raw)
{
    $encoder = $this->encoderFactory->getEncoder($user);
     
    return $encoder->isPasswordValid($user->getPassword(), $raw, $user->getSalt());
}


by 雪洁 2015-12-09 02:53:21 1520 views
我来说几句

相关文章