Auth in Yii Framework

72 Views Asked by At

I dont know why authenticate() is not working in this simply example:

This is one record from my User table

record

model/User.php

class User extends CActiveRecord
{
    public $id;
    public $name;
    public $lastname;
    public $login;
    public $password;
    public $date;

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'user';
    }

    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => 'Imię',
            'lastname' => 'Nazwisko',
            'login' => 'Login',
            'password' => 'Hasło',
            'date' => 'Data rejestracji',
        );
    }

    public function rules()
    {
        return array(
            array('name','required'),
            array('lastname','required'),
            array('login','required'),
            array('password','required'),
            array('date','default',
             'value'=>new CDbExpression('NOW()'),
             'setOnEmpty'=>false,'on'=>'insert')
            );
    }
}

model/UserIdentity.php

class UserIdentity extends CUserIdentity
{
    private $_id;

    public function authenticate()
    {
        $record = user::model()->findAllByAttributes(array('login' => $this->username));
        if($record === null)
        {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        }
        else if($record->password !== md5($this->password))
        {
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        else
        {
            $this->_id = $record->id;
            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId()
    {
        return $this->_id;
    }

}

controller/UserController.php

[...]
public function actionLogin()
    {
        $username = 'janek';
        $password = '1234';
        $identity=new UserIdentity($username,$password);
        if($identity->authenticate())
        {
            echo $identity;
        }
        else
        {
            echo "NOT OK";
        }

    }
[...]

and when action login is requested then always are showing NOT OK. I modify example from yii doc.

1

There are 1 best solutions below

0
On

The problem is that the password in your database is not encrypted, according to the data you presented.

In this case, rewrite your check as

else if($record->password !== $this->password)

instead of

else if($record->password !== md5($this->password))

You should however, be saving your password in an encrypted manner. Of the many options, using md5 is not generally regarded as a safe option. Have a look at the official Yii documentation that shows how to use the Password helper library. http://www.yiiframework.com/doc/guide/1.1/en/topics.auth