I need to hash and store a password from user input in login form in Yii. If I get them thru POST parameters like this:
$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));
this way I expose the uncrypted password in POST request. Other way is to them directly from login form like this:
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,
));
}
but this does not work in my case with authenticating a saved user. The auth function:
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;
}
How to do it in a proper way?
The more troubles appeared as i followed suggest of Samuel - the validating alarm message even before i enter anything, along with hashed password in input field.(see the picture):
When I still enter my username and my password instead of 'proposed' and press 'Create' the form is being sent with not crypted values (from POST request sniffing):
Form Data view source view URL encoded
YII_CSRF_TOKEN:9758c50299b9d4b96b6ac6a2e5f0c939eae46abe
User[username]:igor23
User[password]:igor23
yt0:Create
but nothing is actually stored in db, nor crypted not uncrypted...
Change your create method to:
/**
* 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,
));
}
Change that elseif from this:
elseif ($users->password !== crypt($this->password, $users->password))
To this:
elseif (strcmp(crypt($this->password, 'mysalt123'), $users->password))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.