1

Am trying to update a users password but it fails to save it

This is the controller code:

public function actionChangepassword($id) {
    $model = new UserPass();
    $user = $this->findModel($id);

    if ($model->load(Yii::$app->request->post())) {
        if ($model->validate()) {
            try {
                $user->setPassword($_POST['UserPass']['newpass']);

                if (!$user->save()) {
                    Yii::$app->getSession()->setFlash('success', 'Password changed to ');
                    return $this->redirect(['indexi/'.$user->password]);
                } else {
                    Yii::$app->getSession()->setFlash('error', 'Password not changed');
                    return $this->redirect(['index']);
                }
            } catch (Exception $e) {
                Yii::$app->getSession()->setFlash('error', "{$e->getMessage()}");
                return $this->render('changepassword', [
                    'model' => $model
                ]);
            }
        } else {
            return $this->render('changepassword', [
                'model' => $model
            ]);
        }
    } else {
        return $this->render('changepassword', [
            'model' => $model
        ]);
    }
}

When i check var_dump($_POST['UserPass']['newpass']) it has a value;

When i try changing the part $user->setPassword($_POST['UserPass']['newpass']);

$modeluser->password = $_POST['UserPass']['newpass'];

The password is saved but not hashed,

What could be wrong

This is the setpassword function

public function setPassword($password)
{
    $this->password = Yii::$app->security->generatePasswordHash($password);
}
Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
Geoff
  • 6,277
  • 23
  • 87
  • 197

2 Answers2

1

1) Change

$user->setPassword($_POST['UserPass']['newpass']);

To

$user->newpass = $user->setPassword($_POST['UserPass']['newpass']);

2) Change

public function setPassword($password)
{
    $this->password = Yii::$app->security->generatePasswordHash($password);
}

To

public function setPassword($password)
{
    return Yii::$app->security->generatePasswordHash($password);
}
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
0

Best way is to look how it implemented in advanced template.