【问题标题】:Auth in Yii FrameworkYii 框架中的 Auth
【发布时间】:2015-05-24 18:27:33
【问题描述】:

我不知道为什么 authenticate() 在这个简单的例子中不起作用:

这是我的用户表中的一条记录

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;
    }

}

控制器/UserController.php

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

    }
[...]

当请求操作登录时,总是显示 NOT OK。我修改了 yii doc 中的示例。

【问题讨论】:

    标签: php authentication yii yii-cactiverecord user-identification


    【解决方案1】:

    问题是根据您提供的数据,您的数据库中的密码没有加密。

    在这种情况下,请将您的支票改写为

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

    而不是

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

    但是,您应该以加密方式保存您的密码。在众多选项中,使用 md5 通常不被视为安全选项。查看 Yii 官方文档,其中展示了如何使用密码帮助程序库。 http://www.yiiframework.com/doc/guide/1.1/en/topics.auth

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2016-08-22
      相关资源
      最近更新 更多