Thursday, 15 August 2013




Make Login, Logout and Register Operation in Yii Framework


We will make operation related with database.  So you must know about database before learn this post. And if you want to know how to connect our applcication with databse, you can check my previous posting here. Okey, first we will create 2 table in our database,  table "user" dan table "level"  and this is the script from our table:

CREATE TABLE IF NOT EXISTS `tbl_level_admin` ( `id_level` int(11) NOT NULL AUTO_INCREMENT, `level` varchar(20) NOT NULL, PRIMARY KEY (`id_level`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; INSERT INTO `tbl_level_admin` (`id_level`, `level`) VALUES (1, 'Super Admin'), (2, 'Admin'), (3, 'Customer'); CREATE TABLE IF NOT EXISTS `tbl_user_admin` ( `id_user` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `password` varchar(50) NOT NULL, `enkrip` varchar(50) NOT NULL, `email` varchar(30) NOT NULL, `inisial` varchar(10) DEFAULT NULL, `deskripsi` text, `id_level` int(11) NOT NULL, PRIMARY KEY (`id_user`), KEY `id_level` (`id_level`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; ALTER TABLE `tbl_user_admin` ADD CONSTRAINT `tbl_user_admin_ibfk_1` FOREIGN KEY (`id_level`) REFERENCES `tbl_level_admin` (`id_level`);e "level"

Then, create CRUD operation on table "tbl_user_admin" with gii generete (you can see how to make CRUD generete here). After that, we will connect our form login that include in our yii application with database. This is some step to do it.

- Open directory in application : "protected/components/UserIdentity.php".
- Change code in "function authenticate" to code like this :

public function authenticate() { $user=UserAdmin::model()->find('LOWER(username)=?',array(strtolower($this->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_user; $this->username=$user->username; $this->errorCode=self::ERROR_NONE; } return $this->errorCode==self::ERROR_NONE; }


Finish, now our form login have been connected with our database "tbl_user_admin". After make a login operation, we need to create a register operation. Before create register operation, we must make a validation when user do register. This is our validation for register form :

-  captcha dan data in captcha must match with captcha in the image captcha
- validation in data email
- validation password1 and password2 to decrease mistake when input password
- username, password, email, captcha is required
- give maximum and minimum length in some variable



Okey, now open file in  "protected/controllers/UserAdminControllers.php". Becaruse we want to add captcha in our controllers, we must add captcha  (you can see how to add capthca here) so we must add this code in "UserAdminControllers":

public function actions() {
    return array(
       'captcha'=>array( 'class'=>'CCaptchaAction', 'backColor'=>0xFFFFFF, ),
       'page'=>array( 'class'=>'CViewAction', ),
   );
}
To allow captcha accessed by user, add this code in your method accessRules() :

return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('create','captcha'), 'users'=>array('*'), ), array
After finish modify our controller, now, we will modifiy our model. Open your "protected/models/UserAdmin.php" Change the code like this :

class UserAdmin extends CActiveRecord {
    public $password2;
    public $verifyCode;
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

   public function tableName() { return 'tbl_user_admin'; }
   public function rules() {
      return array(
        array('username, password, email,verifyCode', 'required'),
        array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd')),
        array('id_level', 'numerical', 'integerOnly'=>true),
        array('username, email', 'length', 'max'=>30),
        array('username', 'filter', 'filter'=>'strtolower'),
        array('username','unique'),
        array('password, enkrip', 'length', 'max'=>50,'min'=>5),
        array('password2', 'length', 'max'=>50, 'min'=>5),
        array('password', 'compare','compareAttribute'=>'password2'),
        array('inisial', 'length', 'max'=>10),
        array('email','email'),
        array('deskripsi', 'safe'),
        // The following rule is used by search(). // Please remove those attributes that should not be searched.
       array('id_user, username, email, inisial, deskripsi, id_level', 'safe', 'on'=>'search'), );
}

public function relations() {
    return array( 'idLevel' => array(self::BELONGS_TO, 'LevelAdmin', 'id_level'), );
}

public function attributeLabels() {
    return array( 'id_user' => 'Id User', 'username' => 'Username', 'password' => 'Password', 'email' => 'Email', 'inisial' => 'Inisial', 'deskripsi' => 'Deskripsi', );
}

public function search()
{
 $criteria=new CDbCriteria; $criteria->compare('id_user',$this->id_user);                                                 $criteria->compare('username',$this->username,true); $criteria->compare('password',$this->password,true); $criteria->compare('enkrip',$this->enkrip,true); $criteria->compare('email',$this->email,true); $criteria->compare('inisial',$this->inisial,true); $criteria->compare('deskripsi',$this->deskripsi,true); $criteria->compare('id_level',$this->id_level); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, ));
}

public function validatePassword($password) {
    return $this->hashPassword($password,$this->enkrip)===$this->password;
}

public function hashPassword($password,$salt)
{
    return md5($salt.$password);
}

public function beforeSave()
{
      $isinya=$this->generateSalt();
      $dua=$this->password;
      $this->enkrip=$isinya;
      $this->password=$this->hashPassword($dua,$isinya);
      $this->id_level=3; return true;
}

protected function generateSalt() { return uniqid('',true); } }


Description from the code :

- public $password2; public $verifyCode; this for accomodate variable password2(password confirmation) and verifyCode(captcha).
- public function rules() ===> definition validation from each field.
- public function attributeLabels()===> set some label from field
- variabel public function validatePassword($password)===> function to check if password match or no     with input user when login.
- public function hashPassword($password,$salt)===> function to encrypt password
- public function beforeSave()===> function / behaviour from Yii that alwasy run before we do save some data to database
- protected function generateSalt()===> automatic generate some code to encrypt password

After that, we need to give a link to the form login so that user can access form register. Open in "protected/views/site/login.php" and then add this code :

<p class="hint">
Want To Make New Account?, <?php echo CHtml::link('Register',array('userAdmin/create')); ?>
</p>


After that, open your application. Click login menu and you will see link "register" that will direct us to the register menu.  Click  menu register


DOWNLOAD SOURCE EXAMPLE :CLICK HERE
Unknown Web Developer

No comments:

Post a Comment

Total Pageviews

DjKiRu Initative. Powered by Blogger.