3

사용자를 성공적으로 추가 할 수 있습니다. 암호 해시 사용 중입니다. md5() 그러나 사용자를 업데이트하면 오류가 발생합니다.Yii2에서 사용자 프로필 업데이트 중 암호를 관리하는 방법

<div class="form-group"> 
<?php 
    if($case == 'create') { //this condition called when create user 
     echo $form->field($model, 'password')->passwordInput([ 
      'maxlength' => true, 
      'placeholder' => 'Enter the Password', 
     ]); 
    } 
    else { // during update 
     echo $form->field($model, 'password')->passwordInput([ 
      'maxlength' => true, 
      'placeholder' => 'Enter the Password', 
      'value' => '', 
     ]); 
    } 
?> 
</div> 

<div class="form-group"> 
    <?= $form->field($model, 'confirm')->passwordInput([ 
     'maxlength' => true, 
     'placeholder' => 'Confirm Password', 
    ]) ?> 
</div> 

와 컨트롤러에서 나는 다음과 같은 코드를 사용하고 있습니다 :

public function actionUpdate($id) 
{ 
    $model = $this->findModel($id); 
    $case = "update"; 
    if ($model->load(Yii::$app->request->post())) { 
     $model->save(); 
     return $this->redirect(['view', 'id' => $model->id]); 
    } 
    else { 
     return $this->render('update', [ 
      'model' => $model, 
      'all_users_array' => $all_users_array, 
      'all_groups_array' => $all_groups_array, 
      'case' => $case, 
     ]); 
    } 
} 
을, 나는 다음과 같은 코드를 사용하고 양식 즉,보기에서

public function rules() 
{ 
    return [ 
     [['firstname', 'lastname', 'username', 'email', 'role', 'group_user','status'], 'required'], 
     ['email','email'], 
     [['confirm'], 'compare', 'compareAttribute' => 'password','on'=>'create'], 
     [['firstname', 'lastname', 'username', 'email', 'password', 'confirm', ], 'string', 'max' => 255], 
    ]; 
} 

: 여기

모델의 규칙입니다

오류가 발생합니다 :

Undefined offset: 1 Failed to prepare SQL: UPDATE xbox_user SET password =:qp0, role =:qp1, modified =:qp2, status =:qp3 WHERE id =:qp4

누구든지 코드를 수정해야합니까?

감사합니다. 다음 작동하지 않을 경우

+0

규칙에서 필수 목록에서'암호'를 제거하십시오. '['성 ','성 ','이메일 ','역할 ','그룹 사용자 ','상태 ']'필수 ']' –

+0

내 질문을 업데이트했습니다. – 981

+0

은'create'와'update' 액션을 보여줍니다. –

답변

1

이 글은 scenarios을 사용하는 것이 좋습니다 당신의 다른 요구 사항에도 규칙()을 사용하고 Users.php 모델 파일에 다음 코드를 작성하십시오.

<div class="form-group"> 
<?php 
    if($case == 'create'){ 
    echo $form->field($model, 'password')->passwordInput(['maxlength' => true,'placeholder'=>'Enter the Password']); 
    } 
    else{ 
    echo $form->field($model, 'password')->passwordInput(['maxlength' => true,'placeholder'=>'Enter the Password']); 
} 
?> 
</div> 
<div class="form-group"> 
    <?= $form->field($model, 'confirm')->passwordInput(['maxlength' =>true,'placeholder'=>'Confirm Password']) ?> 
</div> 

및 컨트롤러 파일

, UsersController.php는 다음 코드를 사용합니다 : 귀하의 의견에
public function scenarios(){ 
    $scenarios = parent::scenarios(); 
    $scenarios['create'] = ['firstname', 'lastname', 'username', 'email', 'role', 'group_user','status', 'password','confirm']; 
    $scenarios['update'] = ['firstname', 'lastname', 'username', 'email', 'role', 'group_user','status']; 
    return $scenarios; 
} 

/** 
* @inheritdoc 
*/ 
public function rules() 
{ 
    return [ 
     [['firstname', 'lastname', 'username', 'email', 'role', 'group_user','status', 'password','confirm'], 'required'], 
     ['email', 'filter', 'filter' => 'trim'], 
     ['email', 'unique' ], 
     ['email', 'unique' ,'targetAttribute' => 'email'], 
     ['email', 'required'], 
     ['email', 'email'], 
     ['email', 'unique', 'targetClass' => '\common\models\Users', 'message' => 'This email address has already been taken.'], 
     ['confirm', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords does not match." ], 
     [['firstname', 'lastname', 'username', 'email', 'password', 'confirm', ], 'string', 'max' => 255], 
    ]; 
} 

다음 코드를 사용하여 파일이 코드를 사용하여

public function actionUpdate($id) 
{ 
    $model = $this->findModel($id); 

    $model->scenario = 'update'; // calling scenario of update 
    if ($model->load(Yii::$app->request->post())) { 

     $req_array = yii::$app->request->post(); 
     $role = $req_array['Users']['role'][0]; 

     $model->role = $role; 
     if($req_array['Users']['password'] !== $req_array['Users']['confirm']) 
     { 
      $model->addError('confirm','Password and Confirm should be same.'); 
      $model->password = $req_array['Users']['password']; 
      $model->confirm = $req_array['Users']['confirm']; 
      return $this->render('update', [ 
       'model' => $model, 
       'all_users_array'=>$all_users_array, 
       'all_groups_array'=>$all_groups_array, 
       'case'=>$case, 
      ]); 
     } 
     elseif(($req_array['Users']['password'] == $req_array['Users']['confirm']) && (!empty($req_array['Users']['password']))) 
     { 
      $model->password = MD5($req_array['Users']['password']); 
      $model->save(); 
      return $this->redirect(['view', 'id' => $model->id]); 
     } 
     else 
     { 

      $model->save(); 
      return $this->redirect(['view', 'id' => $model->id]); 
     } 
     } else { 
      $model->password = ''; 
      return $this->render('update', [ 
       'model' => $model, 
       'all_users_array'=>$all_users_array, 
       'all_groups_array'=>$all_groups_array, 
       'case'=>$case, 
      ]); 
     } 
    } 

을, 당신은 오류가 발생하지 않습니다 업데이트시 필요한 비밀번호를 입력하십시오. 비밀번호를 입력 한 경우 비밀번호 확인 및 필수 프로세스가 실행됩니다. 희망이 도움이됩니다.

+0

예, 작동합니다. 고맙습니다! – 981

0

먼저 다음 단계는 그 갱신에 대한 시나리오를 작성하고 시나리오를 시도해 봤어 비밀번호 은 .. 내가 사용자에 대한 간단한 예를 줄 것이다 비교하지 않는 따르십시오이 하나

[['confirm'], 'compare', 'compareAttribute' => 'password','on'=>'create'] 

시도 등록 및 사용자 로그인은 내가 그것을 모델 를 들어 시나리오를 적용하면

<?php 
class User extends Model 
{ 
    public $name; 
    public $email; 
    public $password; 
    public function rules(){ 
     return [ 
      [['name','email','password'],'required'], 
      ['email','email'], 
      [['name', 'email', 'password'], 'required', 'on' => 'register'], 
      ]; 
    } 
    public function scenarios() 
    { 
     $scenarios = parent::scenarios(); 
     $scenarios['login'] = ['name','password'];//Scenario Values Only Accepted 
     return $scenarios; 
    } 
} 
?> 

을 도움이되기를 바랍니다 아래의 코드를 참조하십시오, 우리는의를 설정하는 두 가지 방법을 추가 모델의 cenario. 기본적으로 시나리오는 모델 규칙을 지원합니다.

<?php 
class UserController extends Controller 
{ 
    // APPLY SCENARIOS 
    // scenario is set as a property 
    public function actionLogin(){ 
     $model = new User; 
     $model->scenario = 'login'; 
    } 
    // scenario is set through configuration 
    public function actionRegister(){ 
     $model = new User(['scenario' => 'register']); 
    } 
} 
?> 

enter image description here enter image description here

+0

코드를 업데이트했습니다. 확인하십시오. – 981

+0

아니요. 저에게 맞지 않습니다. – 981

+0

비밀번호 도중 –

2

사용자 모델

public function rules() 
{ 
    return [ 
     [['firstname', 'lastname', 'username', 'email', 'role', 'group_user','status'], 'required'], 
     ['email','email'], 
     [['password', 'confirm'], 'required', 'on' => 'create'], 

     ['confirm', 'compare', 'compareAttribute' => 'password', 'message'=>"Passwords does not match." ], 
     [['firstname', 'lastname', 'username', 'email', 'password', 'confirm', ], 'string', 'max' => 255], 
    ]; 
} 

업데이트 작업

public function actionUpdate($id) 
{ 
    $model = $this->findModel($id); 
    $model->passowrd = ''; 
    $model->confirm = ''; 

    if ($model->load(Yii::$app->request->post())) { 
     $model->role = $model->role[0]; 
     if (empty($model->password) || empty($model->confirm)) { 
      $model->password = $model->getOldAttribute('password'); 
      $model->confirm = $model->getOldAttribute('confirm'); 
     } 
     if ($model->save()) { 
      return $this->redirect(['view', 'id' => $model->id]); 
     } 
    } else { 
     return $this->render('update', [ 
      'model' => $model, 
      'all_users_array'=>$all_users_array, 
      'all_groups_array'=>$all_groups_array, 
     ]); 
    } 
} 

양식

<div class="form-group"> 
    <?= $form->field($model, 'password')->passwordInput(['maxlength' => true,'placeholder'=>'Enter the Password']) ?> 
</div> 
<div class="form-group"> 
    <?= $form->field($model, 'confirm')->passwordInput(['maxlength' => true,'placeholder'=>'Confirm Password']) ?> 
</div> 
1

나는 새 암호를 업데이트하거나 암호가 업데이트 양식에 의해 제공되지 않는 경우 이전을 떠나 핸들 대부분의 프로젝트를 위해 다시 내 자신의 기본 사용자 모델을 가지고있다. 또한 응용 프로그램에 로그인 할 때 사용할 수 있도록 IdentityInterface을 구현합니다.

내 기본 사용자 모델 :

<?php 

namespace app\models; 

use Yii; 
use yii\db\ActiveRecord; 
use yii\web\IdentityInterface; 

class User extends ActiveRecord implements IdentityInterface { 
    const SCENARIO_LOGIN = 'login'; 
    const SCENARIO_CREATE = 'create'; 
    const SCENARIO_UPDATE = 'update'; 

    // We use $hash to save the hashed password we already have saved in the DB 
    public $hash; 
    public $password_repeat; 

    /** 
    * @inheritdoc 
    */ 
    public static function tableName() { 
     return 'user'; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function scenarios() { 
     $scenarios = parent::scenarios(); 
     $scenarios[self::SCENARIO_LOGIN] = ['user', 'password']; 
     $scenarios[self::SCENARIO_CREATE] = ['user', 'password', 'password_repeat', 'email', 'authKey']; 
     $scenarios[self::SCENARIO_UPDATE] = ['user', 'password', 'password_repeat', 'email']; 
     return $scenarios; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function rules() { 
     return [ 
      [['user'], 'string', 'max' => 45], 

      [['email'], 'string', 'max' => 45], 
      [['email'], 'email'], 

      [['password', 'password_repeat'], 'string', 'max' => 60], 

      [['authKey'], 'string', 'max' => 32], 

      [['user', 'password'], 'required', 'on' => self::SCENARIO_LOGIN], 
      [['user', 'password', 'password_repeat', 'email'], 'required', 'on' => self::SCENARIO_CREATE], 
      [['user', 'email'], 'required', 'on' => self::SCENARIO_UPDATE], 

      // Generate a random String with 32 characters to use as AuthKey 
      [['authKey'], 'default', 'on' => self::SCENARIO_CREATE, 'value' => Yii::$app->getSecurity()->generateRandomString()], 

      [['password'], 'compare', 'on' => self::SCENARIO_CREATE, 'skipOnEmpty' => true], 

      [['user'], 'unique'], 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function attributeLabels() { 
     return [ 
      'id' => 'Id', 
      'user' => 'User', 
      'password' => 'Password', 
      'authKey' => 'AuthKey', 
      'email' => 'Email', 
     ]; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function beforeSave($insert) { 
     if (parent::beforeSave($insert)) { 
      if($insert) { 
       $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password); 
      } 
      else { 
       if(strlen($this->password) > 0) { 
        $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password); 
       } 
       else { 
        $this->password = $this->hash; 
       } 
      } 
      return true; 
     } 
     return false; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function afterFind() { 
     $this->hash = $this->password; 
     $this->password = ''; 
     parent::afterFind(); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public static function findIdentity($id) { 
     return self::findOne($id); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public static function findIdentityByAccessToken($token, $type = null) { 
     throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.'); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public static function findByUsername($username) { 
     $model = static::findOne(['user' => $username]); 
     return $model; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function getId() { 
     return $this->getPrimaryKey(); 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function getAuthKey() { 
     return $this->authKey; 
    } 

    /** 
    * @inheritdoc 
    */ 
    public function validateAuthKey($authKey) { 
     return $this->authKey === $authKey; 
    } 

    /** 
    * Validates password 
    * 
    * @param string $password password to validate 
    * @return boolean if password provided is valid for current user 
    */ 
    public function validatePassword($password) { 
     return Yii::$app->getSecurity()->validatePassword($password, $this->hash); 
    } 
} 

당신은 단지 당신의 create, updatelogin 행위에 해당 scenario를 사용할 필요가이 방법 :

$model->scenario = User::SCENARIO_LOGIN; 
$model->scenario = User::SCENARIO_CREATE; 
$model->scenario = User::SCENARIO_UPDATE;