创建新用户时,在POST参数中显示用户名和密码

时间:2013-08-18 15:26:24

标签: php encryption yii authentication

我需要在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,
    ));
}

但在我的情况下,无效验证已保存的用户。 auth功能:

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;
}

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

随着我跟随Samuel的出现,出现了更多麻烦 - 甚至在我输入任何内容之前,验证警报消息,以及输入字段中的散列密码。(见图): more trouble

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

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

但实际上没有任何内容存储在db中,也没有加密未加密...

1 个答案:

答案 0 :(得分: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 ($users->password !== crypt($this->password, $users->password))

对此:

elseif (strcmp(crypt($this->password, 'mysalt123'), $users->password))