1

我需要在 Yii 的登录表单中对用户输入的密码进行哈希处理和存储。如果我通过这样的 POST 参数获取它们:

$model->username=$_POST['User']['username'];
$model->password=crypt($_POST['User']['username']);// salt might be added
if($model->save())
  $this->redirect(array('view','id'=>$model->id));

这样我在 POST 请求中公开了未加密的密码。另一种方法是直接从登录表单发送给他们,如下所示:

public function actionCreate2()
{
    $model=new User;
    $model->username = $form->username;
    $model->password = crypt($form->password);
    if($model->save())
            $this->redirect(array('view','id'=>$model->id));

    $this->render('create',array(
        'model'=>$model,
    ));
}

但这在我的情况下不适用于验证已保存的用户。认证功能:

public function authenticate()
{
    $users = User::model()->findByAttributes(array('username'=>$this->username));

    if($users == null)
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif ($users->password !== crypt($this->password, $users->password))
    //elseif($users->password !== $this->password)
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
        $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;
}

如何以正确的方式做到这一点?

当我遵循塞缪尔的建议时,出现了更多的麻烦 - 甚至在我输入任何内容之前验证警报消息,以及输入字段中的哈希密码。(见图): 更麻烦

当我仍然输入我的用户名和密码而不是“建议”并按“创建”时,表单正在发送且未加密值(来自 POST 请求嗅探):

Form Data   view source   view URL   encoded
YII_CSRF_TOKEN:9758c50299b9d4b96b6ac6a2e5f0c939eae46abe
User[username]:igor23
User[password]:igor23
yt0:Create

但实际上没有任何东西存储在数据库中,也没有加密或未加密......

4

1 回答 1

1

将您的创建方法更改为:

/**
 * Creates a new model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 */
public function actionCreate() {
    $model = new User;

    if (isset($_POST['User'])) {
        $model->attributes = $_POST['User'];
        $model->password = crypt($model->password, 'mysalt123');

        if ($model->save())
            $this->redirect(array('view', 'id' => $model->primaryKey));
    }

    // Reset password field
    $model->password = "";

    $this->render('create', array(
        'model' => $model,
    ));
}

从此改变 elseif:

elseif ($users->password !== crypt($this->password, $users->password))

对此:

elseif (strcmp(crypt($this->password, 'mysalt123'), $users->password))
于 2013-08-19T05:31:51.303 回答