yii 1.x login admin module login frontend

Salve a tutti, mi sono inceppato in un problema, ho una mia applicazione su yii 1.x.x , dove ho un modulo utenti che mi fa da gestione backend con tanto di autenticazione e mi funziona benissimo!, ora ho l esigenza di un login solo per la parte frontend, quindi ho creato per la parte frontend un componente: UserIdentity




<?php


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class UserIdentity extends CUserIdentity

{


	private $_id;

	/**

	 * Authenticates a user.

	 * The example implementation makes sure if the username and password

	 * are both 'demo'.

	 * In practical applications, this should be changed to authenticate

	 * against some persistent user identity storage (e.g. database).

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

		$user=Clienti::model()->findByAttributes(array('username'=>$this->username));


        if($user===null)


            $this->errorCode=self::ERROR_USERNAME_INVALID;


        else if($user->password !==  utf8_encode( crypt($this->password,$user->password))){


            $this->errorCode=self::ERROR_PASSWORD_INVALID;


        }


        else


        {

        	$this->_id= $user->id_cliente;// recupero l'id

				$this->setState('nome',$user->nome);// setto le variabili da passare alla view, per prenderla uso getState

				$this->setState('id_cliente',$user->id_cliente);

				$this->setState('gruppo',$user->gruppo);

				$this->setState('role',$user->role);

            $this->username=$user->username;


            $this->errorCode=self::ERROR_NONE;


        }


 


       


        return !$this->errorCode;

  }


	

}



e un componente: OperatorIdentity




<?php


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class OperatorIdentity extends CUserIdentity

{


	private $_id;

	/**

	 * Authenticates a user.

	 * The example implementation makes sure if the username and password

	 * are both 'demo'.

	 * In practical applications, this should be changed to authenticate

	 * against some persistent user identity storage (e.g. database).

	 * @return boolean whether authentication succeeds.

	 */

	public function authenticate()

	{

		$user=Admin::model()->findByAttributes(array('username'=>$this->username));


        if($user===null)


            $this->errorCode=self::ERROR_USERNAME_INVALID;


        else if($user->password !==  utf8_encode( crypt($this->password,$user->password))){


            $this->errorCode=self::ERROR_PASSWORD_INVALID;


        }


        else


        {

        	$this->_id= $user->id;// recupero l'id

				$this->setState('nome',$user->nome);// setto le variabili da passare alla view, per prenderla uso getState

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

				$this->setState('gruppo',$user->gruppo);

				$this->setState('role',$user->role);

            $this->username=$user->username;


            $this->errorCode=self::ERROR_NONE;


        }


 


       


        return !$this->errorCode;

  }


	

}



nel model frontend ho questo:




<?php


/**

 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.

 */

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(

			'rememberMe'=>'Remember me next time',

		);

	}


	/**

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

	}

}




nel model del modulo utenti (backend) ho:




<?php


/**

 * LoginForm class.

 * LoginForm is the data structure for keeping

 * user login form data. It is used by the 'login' action of 'SiteController'.

 */

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(

			'rememberMe'=>'Remember me next time',

		);

	}


	/**

	 * Authenticates the password.

	 * This is the 'authenticate' validator as declared in rules().

	 */

	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())

		{

			$this->_identity=new OperatorIdentity($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 OperatorIdentity($this->username,$this->password);

			$this->_identity->authenticate();

		}

		if($this->_identity->errorCode===OperatorIdentity::ERROR_NONE)

		{

			$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

			Yii::app()->user->login($this->_identity,$duration);

			return true;

		}

		else

			return false;

	}

}




mentre nel config dell’applicazione ho settato cosi:




// application components

	'components'=>array(

		'user'=>array(

			// enable cookie-based authentication

			'allowAutoLogin'=>true,

		),


		'operator'=>array(

			// enable cookie-based authentication

			'allowAutoLogin'=>true,

		),



quando effetto il login sul backend si collega correttamente verificando che siano presenti i dati sulla tabella clienti!, però se poi vadi a controllare nel modulo ad esempio localhost/sites/app/utenti mi ritrovo già autenticato con i valori della tabella clienti, se ad esempio mi autentico prima dal modulo si collega correttamente alla tabella admin…, ma se vado sulla parte frontend mi trovo già loggato con i dati della tabella admin…, al posto di potermi collegare con riferimento alla tabella clienti!, perchè?

ho corretto il file config cosi e aggiunto il componente WebUser




'user' => array(              // Webuser for the frontend

    	'class'             => 'CWebUser',

    	'loginUrl'          => array('site/login'),

    	'stateKeyPrefix'    => 'frontend_',

		),

		'operator' => array(         // Webuser for the admin area (admin)

    	'class'             => 'CWebUser',

    	'loginUrl'          => array('/utenti/default/login'),

    	'stateKeyPrefix'    => 'admin_',

		),



invece nel modulo backend ho aggiunto questo:




public function beforeControllerAction($controller, $action)

  {

    if(parent::beforeControllerAction($controller, $action))

    {

    	


        // Make 'adminUser' the main user in this module.

            // Frontend user is available as 'Yii::app()->frontendUser'.

            Yii::app()->setComponent('frontendUser', Yii::app()->user);

            Yii::app()->setComponent('user', Yii::app()->operator);

      return true;

    }

    else

      return false;

  	}

  }



Pare che funzioni, però ho notato una cosa, se apro google chrome e mi loggo come user funziona, poi apro un’altra tab di crhome e vado sul modulo mi chiede di loggarmi come volevo…, mi loggo come admin e va tutto bene!..quindi apparentemente ho due sessioni diverse, però se ad esempio faccio il logout o da user o da admin(dal modulo) cadono tutte e due le sessioni perchè?, se invece apro una sessione utente da crhome, una da opera, e una sessione admin da mozilla!..se faccio i logout funziona tutto regolarmente

Nei due controller frontend e backend, nell azione di logout ho settato cosi e tutto funziona! per chi possa incappare nel problema :)




Yii::app()->user->logout(false);