• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

GhazaliTajuddin.com

Another Kuantan Blogger

  • Home
  • Blog
    • Kuantan
    • Foods
    • Technology
    • Health
  • Stock Photography
    • Senarai Microstock Agency
    • Membuka akaun contributor Shutterstock.com
    • Tips untuk 10 keping gambar pertama Shutterstock.com
    • Mengapa Shutterstock.com reject gambar / submission
    • Model Release
    • Bagaimana withdraw earning daripada Fotolia
    • Bagaimana untuk mengisi keyword kepada imej dengan menggunakan Adobe Photoshop
You are here: Home / General / Understanding Yii Basic User Authentication

Understanding Yii Basic User Authentication

March 26, 2012 by ghazalitajuddin 1 Comment

Yii Framework
Yii Framework

Basicly, Yii basic skeleton already come with aunthentication system which is very simple by checking username and password both admin or demo.

The default authentication files is

  1. UserIdentity.php
  2. LoginForm.php
  3. SiteController.php
  4. Login.php
The process description
  1. The process started when user click the login menu.
  2. When user click the Login menu, the SiteController will launch actionLogin() method. (SiteController.php)
  3. The actionLogin() method will initiate new object from LoginForm model, called $model.
  4. The actionLogin() method will check $_POST[‘LoginForm’] if carry data
  5. If $_POST[‘LoginForm’] carry data, assign $model->attributes = $_POST[‘LoginForm’]
  6. The new assign $model->attributes will be validate by calling $model->validate() and $model->login(). $model->login() is inherits from LoginForm class which check the user is valid or not. (LoginForm.php)
  7. In Login() method a new instant created,
    1.  $this->_identity=new UserIdentity($this->username,$this->password); (UserIdentity.php)
    2.  $this->_identity->authenticate(); (UserIdentity.php)
    3. The cookie is set here too. (LoginForm.php)
  8. If both check on $model->attributes && $model->login() is valid, redirect to previous page.
  9. else is not valid, return to Login page (login.php) with error notification.
The page detail

1. root/webapps/protected/components/UserIdentity.php

[php]

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;
else if($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;
}
}

[/php]

2. root/webapps/protected/model/LoginForm.php

[php]

<?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;
}
}

[/php]

3. root/webapps/protected/controllers/SiteController.php

[php]

…

/**
* Displays the login page
*/
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);
}
// display the login form
$this->render(‘login’,array(‘model’=>$model));
}

…

[/php]

4. root/webapps/protected/views/site/login.php

[php]

<?php
$this->pageTitle=Yii::app()->name . ‘ – Login’;
$this->breadcrumbs=array(
‘Login’,
);
?>

<h1>Login</h1>

<p>Please fill out the following form with your login credentials:</p>

<div class="form">
<?php $form=$this->beginWidget(‘CActiveForm’, array(
‘id’=>’login-form’,
‘enableClientValidation’=>true,
‘clientOptions’=>array(
‘validateOnSubmit’=>true,
),
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>

<div class="row">
<?php echo $form->labelEx($model,’username’); ?>
<?php echo $form->textField($model,’username’); ?>
<?php echo $form->error($model,’username’); ?>
</div>

<div class="row">
<?php echo $form->labelEx($model,’password’); ?>
<?php echo $form->passwordField($model,’password’); ?>
<?php echo $form->error($model,’password’); ?>
<p class="hint">
Hint: You may login with <tt>demo/demo</tt> or <tt>admin/admin</tt>.
</p>
</div>

<div class="row rememberMe">
<?php echo $form->checkBox($model,’rememberMe’); ?>
<?php echo $form->label($model,’rememberMe’); ?>
<?php echo $form->error($model,’rememberMe’); ?>
</div>

<div class="row buttons">
<?php echo CHtml::submitButton(‘Login’); ?>
</div>

<?php $this->endWidget(); ?>
</div><!– form –>

[/php]

Filed Under: General, Technology Tagged With: Authentication, CakePHP, Controller, Framework, Kuantan, kuantan programmer, kuantan software developer, kuantan webmaster, Login, model, MVC, OOP, PHP, View, wordpress, yii, Yii Framework

Reader Interactions

Comments

  1. disbelieve864 says

    August 8, 2012 at 3:12 pm

    Thank you in advance to the assist!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

“Solat. Sabar. Syukur. Senyum. Sedekah.”

For Collaboration, Events & Review, kindly contact me at +6016[-]9212092 or click Whatsapp button on this page.

Sponsor

Recent Posts

BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.

User Roles And Permissions Without Package Laravel 10

Laravel Many To Many Relationship

Makan malam bersama keluarga di Awangan Palace

Sarapan pagi di Warung Gulai Kawah

Recent Comments

  • helmi on Personal Tips Berhenti Merokok
  • ghazalitajuddin on Personal Tips Berhenti Merokok
  • helmi on Personal Tips Berhenti Merokok
  • ghazalitajuddin on Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.
  • ghazalitajuddin on Air tangki radiator Proton Exora cepat kering? Cuba tukar penutup radiator!
  • Mal on Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.
  • Firdaus on Air tangki radiator Proton Exora cepat kering? Cuba tukar penutup radiator!

My Link

  • Takaful Insurance Web

JJCM

Patin Tempoyak Frozen Resepi Temerloh

Nasi Lemak Kukus Restoran Zaman. Otai masih berbisa.

Kuih Keria Viral di Kuantan???

Sarapan pagi di Warung Gulai Kawah

Kopi Acah-acah Diet

Tags

bebas rokok berhenti merokok breakfast Controller Framework Gezzeg Photography & Design health jalan-jalan cari makan jalan-jalan cari makan kuantan jjcm jjcm kuantan Jurufoto Kuantan Kuantan Kuantan Photographer kuantan programmer kuantan web developer kuantan webmaster laravel merokok merbahayakan kesihatan model MVC nikmat rokok OOP Pahang Pahangtourism pahang tourism Photo Manipulation PHP rajalanun retired smoking revisit pahang 2018 shutterstock stop smoking stop smoking tips stop smoking withdrawal symptom tips tips berhenti merokok View visit malaysia 2020 visit pahang visitpahang white wordpress yii Yii Framework

Recent Posts

  • BadMethodCallException Method Illuminate\Database\Eloquent\Collection::roles does not exist.
  • User Roles And Permissions Without Package Laravel 10
  • Laravel Many To Many Relationship
  • Makan malam bersama keluarga di Awangan Palace
  • Sarapan pagi di Warung Gulai Kawah

Copyright © 2025 — Ghazali Tajuddin • All rights reserved. •