YiiPassword扩展使用

时间:2013-03-30 02:50:20

标签: yii yii-extensions

我将YiiPassword 扩展名解压缩为protected/components/YiiPassword

main.php:

    .
    .
    .
    'import'=>array(
            'application.models.*',
            'application.components.*',
            'application.components.YiiPassword.*',
            'application.helpers.*',

    ),
    .
    .
    .

User.php:(型号)

.    
.
.
public function behaviors()
{
    return array(
        "APasswordBehavior" => array(
            "class" => "APasswordBehavior",
            "defaultStrategyName" => "bcrypt",
            "strategies" => array(
                "bcrypt" => array(
                    "class" => "ABcryptPasswordStrategy",
                    "workFactor" => 14
                ),
                "legacy" => array(
                    "class" => "ALegacyMd5PasswordStrategy",
                )
            ),
        )
    );
}
.
.
.

Ans还将三个字段添加到 tbl_user

salt - 保存用于散列密码的每用户salt

密码 - 保留哈希密码(已存在)

passwordStrategy - 保留此用户的当前密码策略名称

requiresNewPassword - 一个布尔字段,用于确定用户是否应更改其密码

现在我只想使用 bcrypt ,如何编码用户密码,验证用户登录?

2 个答案:

答案 0 :(得分:1)

您只需要检索用户并调用verifyPassword方法即可!这种方法的描述:

  

将给定密码与此模型的存储密码进行比较

所以你可以这样做:

$user = User::model()->findByPK(1);
if($user->verifyPassword("password")){
    //Password verified
}

答案 1 :(得分:0)

<强>解决

以下测试成功完成, ABcryptPasswordStrategyTest.php:

<?php
Yii::import("application.components.passwordStrategy.*");
Yii::import("application.models.*");

/**
 * Tests for the {@link ABcryptPasswordStrategy} class.
 * @author Charles Pick
 * @package packages.passwordStrategy
 */
class ABcryptPasswordStrategyTest extends CTestCase
{
    public function testEncode()
    {
        $user=User::model()->findByAttributes(array('username'=>'user'));
        $strategy = new ABcryptPasswordStrategy();
        $strategy->getSalt(true);

        $user->password = 'pass';
        $user->save();

        $this->assertTrue($user->verifyPassword("pass"));
    }
}

more info