[Ask] Membuat login di Yii

Minta bantuannya buat agan" akang" para master yang suka develop pake Yii,

Setelah install yii, saya browse localhost/project/ muncul web blog sample bawaannya yii kan, nah setalah coba login pake "demo/demo admin/admin" ternyata masih default/redirect ke halaman index, saya udah ikutin tutorial di yii nya, berikut file yang saya edit dan buat:

Saya edit file project/protected/components/UserIdentity.php dari code :




<?php 

class UserIdentity extends CUserIdentity 

{ 

  public function authenticate() 

    { 

        $users=array( 

            // username => password 

            'demo'=>'demo', 

            'admin'=>'admin', 

        ); 

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

            $this->errorCode=self::ERROR_USERNAME_INVALID; 

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

            $this->errorCode=self::ERROR_PASSWORD_INVALID; 

        else 

            $this->errorCode=self::ERROR_NONE; 

        return !$this->errorCode; 

    } 

} 

?>



Di edit menjadi code :




<?php 

class UserIdentity extends CUserIdentity 

{ 

   private $_id; 

  

    public function authenticate() 

    { 

        $username=strtolower($this->username); 

        $user=User::model()->find('LOWER(username)=?',array($username)); 

        if($user===null) 

            $this->errorCode=self::ERROR_USERNAME_INVALID; 

        else if(!$user->validatePassword($this->password)) 

            $this->errorCode=self::ERROR_PASSWORD_INVALID; 

        else 

        { 

            $this->_id=$user->id; 

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

            $this->errorCode=self::ERROR_NONE; 

        } 

        return $this->errorCode==self::ERROR_NONE; 

    } 

  

    public function getId() 

    { 

        return $this->_id; 

    } 

} 

?>



Setelah itu saya buat tabel "tbl_user" untuk attribute nya sama dengan yang ada di tutorial Yii, setalah itu saya buka Gii untuk generate model "tbl_user", kemudian saya edit file user.php yang ada di project/protected/models/user.php, ini tampilan code user.php sebelum di edit:




<?php 


class User extends CActiveRecord 

{ 

      

    public static function model($className=__CLASS__) 

    { 

        return parent::model($className); 

    } 


    public function tableName() 

    { 

        return 'tbl_user'; 

    } 


     

    public function rules() 

    { 

        // NOTE: you should only define rules for those attributes that 

        // will receive user inputs. 

        return array( 

            array('username, password, salt, email, profile', 'required'), 

            array('username, password, salt, email, profile', 'length', 'max'=>128), 

            // The following rule is used by search(). 

            // Please remove those attributes that should not be searched. 

            array('id, username, password, salt, email, profile', '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' => 'Username', 

            'password' => 'Password', 

            'salt' => 'Salt', 

            'email' => 'Email', 

            'profile' => 'Profile', 

        ); 

    } 


    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('salt',$this->salt,true); 

        $criteria->compare('email',$this->email,true); 

        $criteria->compare('profile',$this->profile,true); 


        return new CActiveDataProvider($this, array( 

            'criteria'=>$criteria, 

        )); 

    } 

}

dan code ini saya sisipkan file user.php :




<?php 


class User extends CActiveRecord 

{ 

     

      public function validatePassword($password) 

       { 

             return $this->hashPassword($password,$this->salt)===$this->password; 

       } 

  

       public function hashPassword($password,$salt) 

       { 

             return md5($salt.$password); 

       } 

      

    public static function model($className=__CLASS__) 

    { 

        return parent::model($className); 

    } 


    public function tableName() 

    { 

        return 'tbl_user'; 

    } 


     

    public function rules() 

    { 

        // NOTE: you should only define rules for those attributes that 

        // will receive user inputs. 

        return array( 

            array('username, password, salt, email, profile', 'required'), 

            array('username, password, salt, email, profile', 'length', 'max'=>128), 

            // The following rule is used by search(). 

            // Please remove those attributes that should not be searched. 

            array('id, username, password, salt, email, profile', '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' => 'Username', 

            'password' => 'Password', 

            'salt' => 'Salt', 

            'email' => 'Email', 

            'profile' => 'Profile', 

        ); 

    } 


    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('salt',$this->salt,true); 

        $criteria->compare('email',$this->email,true); 

        $criteria->compare('profile',$this->profile,true); 


        return new CActiveDataProvider($this, array( 

            'criteria'=>$criteria, 

        )); 

    } 

}



setalah sampai step itu, saya kurang ngerti lagi, dan saya liat ada code tambahan yang harus disisipkan :




$identity=new UserIdentity($username,$password); 

$identity->authenticate(); 

switch($identity->errorCode) 

{ 

    case UserIdentity::ERROR_NONE: 

        Yii::app()->user->login($identity); 

        break; 

    ...... 

}  



Code di atas harus disisipkan di file mana ya?

Inti dari permasalahan ini, saya ingin login memakai record bawaan tabel yang saya buat, dan ketika login berhasil, halaman yang dituju bukan lagi ke index melainkan halaman site/user/admin yang sudah saya buat memakai Gii, sekalai lagi saya mohon pencerahannya dari agan" akang" sekalian.

trims.

kebetulan banget lagi nyari nih bahasan… tapi sayang gada yang bisa jawab…

padahal butuh banget

:(

coba bantu ya :D


$identity=new UserIdentity($username,$password); 

$identity->authenticate(); 

switch($identity->errorCode) 

{ 

    case UserIdentity::ERROR_NONE: 

        Yii::app()->user->login($identity); 

        break; 

    ...... 

}  

coding ini fungsi nya apa y gan? itu untuk validasi user bukan?

setahu ane, punya ane g ada baris coding ini?? ??? ao itu cara lain ya :D hehe…

klo boleh ane bagi nih, login ane kyk gini…

ini di file Useridentity.php ane :


class UserIdentity extends CUserIdentity

{

	/**

	 * 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()

	{

		$users=array(

			// username => password

			'demo'=>'demo',

			'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->errorCode=self::ERROR_NONE;

		return !$this->errorCode;

	}*/

	

	private $_id;

	public function authenticate()

	{

		$username = ($this->username);

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

		$pwd = USER::model()->findByAttributes(array('PASSWORD'=>$this->password));

		if ($user==null)

			$this->errorCode=self::ERROR_USERNAME_INVALID;

		else if (!$user->validatePassword($this->password))

			$this->errorCode=self::ERROR_PASSWORD_INVALID;

		

		else

		{

			$this->_id = $user->USER_ID;

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

			$this->password = $user->PASSWORD;

			

			$this->errorCode=self::ERROR_NONE;

		}

		return $this->errorCode==self::ERROR_NONE;

	}

	

	public function getId()

	{

		return $this->_id;

	}

}

di model, anek kasih tambahan beberapa method function tambahan :




protected function afterValidate()

	{

		parent::afterValidate();

		$this->PASSWORD = $this->encrypt($this->PASSWORD);

	}	 

	

	protected function encrypt($value)

	{

		return md5 ($value);

	}	


public function validatePassword ($password)

	{

		return ($this->PASSWORD == md5($password));

	}

	

	protected function beforeSave ()

	{

		if (parent::beforeSave())

		{

			if ($this->isNewRecord)

			{

				$this->setAttribute('password',md5($this->PASSWORD));

			}	

			return true;

		}

		return false;

	}



kalau untuk mengarahkan ke halaman yang diinginkan setelah login, agan buka aja file sitecontroller.php disitu ada method :




public function actionLogin()

	{

		$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()->user->returnUrl);   <---- disini

		}

		// display the login form

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

	}



Potongan code ini:




$identity=new UserIdentity($username,$password); 

$identity->authenticate(); 

switch($identity->errorCode) 

{ 

    case UserIdentity::ERROR_NONE: 

        Yii::app()->user->login($identity); 

        break; 

    ...... 

}  



ada di model LoginForm di function authenticate()

nice post ;D