在 Yii 应用程序中获取用户 ID 的问题


Issue with getting user id in Yii application

我有一个在生产环境中运行的网站,它运行良好,我正在对代码进行一些更改,所以我将其复制到本地主机。该网站具有用户管理系统,需要登录。用户登录后,他们将被重定向到 mysite.com/admin/index。

正在进行用户验证,并且对 UserIdentity 类中的类进行身份验证,错误代码为 0。但是,当用户转到WebUser类时,当我检查$this->id时,它会返回一个空值。此外,Yi::app()->user->id 不存在。

以下是我的代码的相关部分:

主要.php

'components'=>array(
        'user'=>array(
            // enable cookie-based authentication
            // 'allowAutoLogin'=>true,
            'class' => 'WebUser',
            'loginUrl'=>array('site/login'),
        ),
        // uncomment the following to enable URLs in path-format
        'urlManager'=>array(
            'urlFormat'=>'path',
            'showScriptName'=>false,
            'rules'=>array(
                '<controller:'w+>/<id:'d+>'=>'<controller>/view',
                '<controller:'w+>/<action:'w+>/<id:'d+>'=>'<controller>/<action>',
                '<controller:'w+>/<action:'w+>'=>'<controller>/<action>',
            ),
        ),

在用户标识中.php

private $_group;
private $_id;
public function getId(){
  return $this->_id;
}
public function authenticate($seeker = false, $queryid = false){
  //Retrieve seeker Login
  $record=User::model()->findByAttributes(array('login_name'=>$this->username, 'status' => 0));
  //Invalid username
  if($record===null){
    $this->errorCode=self::ERROR_USERNAME_INVALID;
  }
  //Invalid password
  else if($record->password !== $record->encryptPassword($this->password) && $record->password !== $record->encryptPassword($this->password, true)){
    $this->errorCode=self::ERROR_PASSWORD_INVALID;
  }
  //Valid login
  else{
    //Use new encryption
    if($record->password === $record->encryptPassword($this->password, true))
      $record->resetPassword($this->password);
    $this->_id       = $record->id;
    $this->_group    = $record->group;
    $this->errorCode = self::ERROR_NONE;
  }
  if($this->errorCode == self::ERROR_NONE){
    $auth=Yii::app()->authManager;
    try{ $role=$auth->createRole($this->_group); } catch(Exception $e){}
    if(!$auth->isAssigned($this->_group,$this->_id)){
      if($auth->assign($this->_group,$this->_id)){
        Yii::app()->authManager->save();
      }
    }
  }
  return !$this->errorCode;
}

在我的 SiteController.php 中,当我在登录后检查用户 ID 时,它会返回正确的值,但在用户被重定向到 admin/index 并且我检查用户 id 的值后,它不会显示任何值。

有人可以建议我缺少什么吗?

下面的代码保存网址状态,
请求admin/edit/3 ->重定向到 login page -> 重定向到 admin/edit/3
请求login page ->重定向admin/index

$this->redirect(Yii::app()->getUser()->getReturnUrl('admin/index'));

如果只从你的代码中决定,而其他一切都无关紧要,看起来这个验证

Yii::app()->user->returnUrl == '/index.php'

总是假的。您可以通过在调试器中的此品脱处停止代码或简单地放置"转储停止代码":)来简单地调试它

var_dump(
    Yii::app()->user->returnUrl == '/index.php',
    Yii::app()->user->returnUrl
);
die();

在此行之前

$this->redirect(Yii::app()->user->returnUrl == '/index.php'? '/admin/index': Yii::app()->user->returnUrl);