Yii:User Auth thru db not working - 检索用户模型实例时出现“Null”

时间:2013-08-17 10:44:39

标签: database authentication yii

我想做用户auth thru db。我用一些字段创建了db User并插入了一些记录。 username=adminpassword=admin; username=demopassword=demo。 现在我已经应用了gii从我的表格中创建了一个“User”模型,并将模型保存在模型组件文件夹中。 在 UserIdentity.php 中进行模型检索,但转储显示检索到的对象为 NULL !有趣的是,我在我的自定义控制器中完成了相同的检索,而且相当有效!

  public function authenticate()
{
    /* $users=array(
        // username => password
        'demo'=>'demo',
        'admin'=>'admin',
    ); */       
    $users = User::model()->findByAttributes(array('username'=>$this->username));
    var_dump($users);
    // $username=strtolower($this->username);
    // $users=User::model()->find('LOWER(username)=?',array($username));

    if(!isset($users[$this->username]))
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    elseif($users[$this->username]->password !== $this->password)
        $this->errorCode=self::ERROR_PASSWORD_INVALID;
    else
        $this->errorCode=self::ERROR_NONE;
    return !$this->errorCode;
}

出了什么问题,我是否需要在main.php属性'user'配置中提及此用户模型/组件?如何? 此外,User类显然扩展了CActiveRecord,而不是CWebUser。这是正常的吗?

 class User extends CActiveRecord
 {

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

/**
 * @return string the associated database table name
 */
public function tableName()
{
    return 'user';
}

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('username, password, created', 'required'),
        array('role, ban', 'numerical', 'integerOnly'=>true),
        array('username, password', 'length', 'max'=>255),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('id, username, password, created, role, ban', 'safe', 'on'=>'search'),
    );
}

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
    );
}

public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'username' => 'Name',
        'password' => 'Password',
        'created' => 'Created',
        'role' => 'Role',
        'ban' => 'Ban',
    );
}

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('username',$this->username,true);
    $criteria->compare('password',$this->password,true);
    $criteria->compare('created',$this->created,true);
    $criteria->compare('role',$this->role);
    $criteria->compare('ban',$this->ban);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

问题在于,当我尝试使用这种数据库插件登录时(确实没有转储行),我总是用户名或密码不正确

LoginForm.php :     

private $_identity;

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'),
    );
}
public function attributeLabels()
{
    return array(
        'rememberMe'=>'Remember me next time',
    );
}
public function authenticate($attribute,$params)
{
    if(!$this->hasErrors())
    {
        $this->_identity=new UserIdentity($this->username,$this->password);
        if(!$this->_identity->authenticate())
            $this->addError('password','Incorrect username or password.');
    }
}
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;
  }
 }

以下是其他控制器中用于从模型User转储'admin'记录的代码:

$username = 'admin';
    $users = User::model()->findByAttributes(array('username'=>$username));
    foreach ($users->attributes as $key=>$value){
            echo  $key . ' => '. $value. '</br>';
         } 
    Yii::app()->end();

结果非常好:

id => 1
username => admin
password => admin
created => 2013-08-16 00:00:00
role => 1
ban => 0

1 个答案:

答案 0 :(得分:1)

问题似乎在以下部分:

if(!isset($users[$this->username]))
    $this->errorCode=self::ERROR_USERNAME_INVALID;
elseif($users[$this->username]->password !== $this->password)
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
else
    $this->errorCode=self::ERROR_NONE;
return !$this->errorCode;

尝试将其更改为:

if($users == null))
    $this->errorCode=self::ERROR_USERNAME_INVALID;
elseif($users->password !== $this->password)
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
else
    $this->errorCode=self::ERROR_NONE;
return !$this->errorCode;

$users变量是一个对象,不能用作$users[$this->username]数组包含登录信息的原始脚本中的数组($users)。当您将其更改为通过db进行身份验证时,该变量现在包含与登录表单中输入的用户名相对应的数据库行(如果有)...