[Problema]Autenticação De Login

Boa noite, eu tenho uma tabela de usuários, nessa tabela eu salvos os dados cadastrados e utilizo o Password Helper para gerar a hash da senha, no UserIdentity eu utilizo o mesmo Helper para comparar as senhas ao logar.

Meu problema é que ele gera hashs diferentes e por isso não loga, testei de outras formas como por exemplo apenas md5 ou sha1, continua gerando hashs diferentes. Porém, gravando a senha sem criptografia ele consegue logar normalmente.

Alguém tem alguma ideia do que possa ser? Seguem os códigos abaixo.




<?php


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class UserIdentity extends CUserIdentity

{

	/**

	 * Authenticates a user.

	 * The example implementation makes sure if the username and password

	 * are both 'demo'.

	 * In practical applications, this should be changed to authenticate

	 * against some persistent user identity storage (e.g. database).

	 * @return boolean whether authentication succeeds.

	 */

	private $_id;

	public function authenticate()

	{

		

        $record=Usuario::model()->findByAttributes(array('EMAIL'=>$this->username));

        if($record===null)

            $this->errorCode=self::ERROR_USERNAME_INVALID;

        else if($record->SENHA!==CPasswordHelper::verifyPassword($this->password, $record->SENHA))

            $this->errorCode=self::ERROR_PASSWORD_INVALID;

        else

        {

            $this->_id=$record->CODIGO_USUARIO;

            $this->setState('title', $record->title);

            $this->errorCode=self::ERROR_NONE;

        }

        return !$this->errorCode;

    }

 

    public function getId()

    {

        return $this->_id;

    

	}

}



Função que gera o hash da senha para gravar no banco.




public function beforeSave()

	{

		$this->SENHA = CPasswordHelper::hashPassword($this->SENHA);

		return true;

	}






<?php


/**

 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.

 */

class LoginForm extends CFormModel

{

	public $username;

	public $password;

	public $rememberMe;


	private $_identity;


	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			// username and password are required

			array('username, password', 'required'),

			// rememberMe needs to be a boolean

			array('rememberMe', 'boolean'),

			// password needs to be authenticated

			array('password', 'authenticate'),

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

			'rememberMe'=>'Lembrar-me',

		);

	}


	/**

	 * Authenticates the password.

	 * This is the 'authenticate' validator as declared in rules().

	 */

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			if(!$this->_identity->authenticate())

				$this->addError('Senha', 'Usuário ou senha incorretos.');

			

		}

	}


	/**

	 * Logs in the user using the given username and password in the model.

	 * @return boolean whether login is successful

	 */

	public function login()

	{

		if($this->_identity===null)

		{

			$this->_identity=new UserIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===UserIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}

}



Cara, acho que trocar:


else if($record->SENHA!==CPasswordHelper::verifyPassword($this->password, $record->SENHA))

Por isso:


else if(!CPasswordHelper::verifyPassword($this->password, $record->SENHA))

Pode resolver seu problema.

O método verifyPassword retorna bool e do jeito que vc fez, vc compara a senha salva no BD com o retorno da função. Desse jeito, vai retornar sempre false.

Abs

Eu havia esquecido isso, porém como eu disse, testei com outras criptografias, como md5 e sha1…ele gera diferentes hashs da mesma string. O problema persiste.

O problema está no seu beforeSave que está salvando novamente a senha cada vez que você for salvar ou depois de uma validação.

Verifique se o campo é novo e veja se resolve seu problema.




public function beforeSave()

    {

     	if($this->isNewRecord)

     	{	 		

        	$this->SENHA = CPasswordHelper::hashPassword($this->SENHA);            

        }

        return true;

    }