检查密码并使用FOSUserBundle手动创建用户

时间:2012-02-28 09:53:37

标签: symfony passwords fosuserbundle

我在我的应用程序中使用FOSUserBundle。我想通过HTTP服务做两件事:

  1. 检查密码。该服务可能如下所示(密码不会被加密):

    public function checkPasswordValidity($userId, $password) {
        $user = $this->getDoctrine()
            ->getRepository('MyCompany\UserBundle\Entity\User')
            ->find($userId);
    
        if (specialFunction($user , $password))
            echo 'Valid Password';
        else
            echo 'Invalid Password';
    }
    
  2. 通过其他HTTP服务创建新用户。参数将是用户名和密码。

3 个答案:

答案 0 :(得分:62)

  1. 检查密码:

    $encoder_service = $this->get('security.encoder_factory');
    $encoder = $encoder_service->getEncoder($user);
    $encoded_pass = $encoder->encodePassword($password, $user->getSalt());
    
    //then compare    $user->getPassword() and $encoded_pass
    
  2. 创建新用户:

    $userManager = $this->get('fos_user.user_manager');
    $user = $userManager->createUser();
    $user->setUsername($login);
    $user->setPlainPassword($pass);
    ...
    $userManager->updateUser($user);
    

答案 1 :(得分:6)

对我而言:

$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt()) {}

我没有测试第二个问题,但我认为它已经是answered了。

答案 2 :(得分:0)

手动添加新用户:

登录 phpmyadmin ,访问 fos_user_user 表,点击插入>填写字段,用户名,电子邮件,角色等。

使用此php脚本生成salt和密码:

<?php 

$salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);

echo "Salt used: " . $salt ."<br/>";

echo "<br/>";

$password = 'adminpasswordhere';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);

for ($i=1; $i<5000; $i++) {
    $digest = hash('sha512', $digest.$salted, true);
}

$encodedPassword = base64_encode($digest);

echo "Password used: " . $password ."<br/>";

echo "<br/>";

echo "Encrypted Password: " . $encodedPassword ."<br/>";


?>

享受!