Проблемы С Авторизацией

Начинаю разбираться с Yii (запускаю его локально под denwer-ом), вылезла проблема с авторизацией, перекопал все форумы,

но проблемы решить так и не смог.

Вызываю метод login для пользователя, но все равно при дальнейшей проверке в методе beforeAction выдает что пользователя нет.

Настройки сессии прописал следующим образом:




	'components'=>array(

     'session' => array(

        'autoStart' => true,

        /*'timeout' => 300,*/

        'cookieMode' => 'only',

     ),

   	'user'=>array(

			// enable cookie-based authentication

			'allowAutoLogin'=>true,

		),



Код identity стандартный:




class UserIdentity extends CUserIdentity

{

  private $_id;

 	/**

	 * Authenticates a user.

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

		$users=array(

			// username => password

			'admin'=>'admin',

		);

		if(!isset($users[$this->username]))

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		elseif($users[$this->username]!==$this->password)

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		else {

		  $this->_id = $this->username;

		  $this->setState('id', $this->_id);

			$this->errorCode=self::ERROR_NONE;

    }

		return !$this->errorCode;

	}


  public function getId()

  {

    return $this->_id;

  }

}



Код самой авторизации тоже стандартный:




	public function actionLogin()

	{

	  $this->layout = '//layouts/simple';

		$model=new LoginForm;


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm']))

		{

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login()) {

				$this->redirect(Yii::app()->createUrl('site/index'));

      }

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}



Добавил логи после авторизации и в начало метода beforeAction:




      	Yii::log('Session id: ' . Yii::app()->session->sessionID, 'info');

      	Yii::log('User id:' . Yii::app()->user->getId(), 'info');

      	Yii::log('Is guest: ' . Yii::app()->user->isGuest, 'info');

      	Yii::log('Session: ' . print_r(Yii::app()->session, true), 'info');

      	Yii::log('User' . print_r(Yii::app()->user, true), 'info');



Вот что выводит сразу после авторизации:

В beforeAction же уже этих данных нет:

Даже наличие файла с сессии проверил. Файл есть, данные в нем тоже есть:

Ну и в догонку код LoginForm:




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(

			'username'=>'Логин',

			'password'=>'Пароль'

		);

	}


	/**

	 * 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('password','Incorrect username or password.');

		}

	}


	/**

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

	}

}



У меня нечто похожее наблюдалось в гуглохроме, в случае если доменное имя не имело TLD (ну, типа, http://mysite/).

Просто терялся кукис.

Вылечил тупо изменением домена на mysite.local

Прописал в etc/hosts:

127.0.0.1 mysite.ru

Соответственно открыл по адресу:

mysite.ru - все тоже самое, при этом проблема не только в хроме, но и в IE, и в Opera (в FF не тестил, но скорее всего и там).

Да и не похоже что cookie теряется. Session id то правильный выдается в логи, в beforeAction. А вот user почему то гестовый и без id-ника.

Кстати, а вот это

оно откуда?

Собственно, вот эта строчка смущает:


$this->setState('id', $this->_id);

Авторизация у сгенерённого yiic webapp приложения без изменений работает? Если да — баг в приложении или конфиге. Если нет — баг в фреймворке или настройках сервера.

Пробовал в трех вариантах, сначала просто автосгенерированный, потом добавил $id и getId, потом добавил setState. Не работало ни в одном из трех.

Попробовал сгенерировать новое приложение и проверить авторизацию. Работает только если поставить галочку "Запоминать пользователя". Видимо где то в настройках сервера проблема. Какие опции нужно проверять?

Похоже какая-то проблема с сессиями…