Yii 1.1: How to create front and admin side login form

16 followers

In this WIKI you can learn how to create front and admin login form, using database.

Scenario:

As a beginner once you setup default yii project, next step will be how to change this static login form to dynamic, i.e. username and password comes from database.

Default setup:

I am using this article to manage project directory structure for front and admin. Thanks Andy for this WIKI. Follow all the steps and you will have separate front and admin panels like:

  • http://localhost/index.php // Front End
  • http://localhost/backend.php // Admin Panel

I am using 2 different models to handle front and admin user database.

  1. User
  2. AdminUser

LoginForm:

Path: models/LoginForm.php

Here i am adding new variable to the class. i.e. userType

class LoginForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe;
    public $userType; // added new member
 
    private $_identity;
 
    public function __construct($arg='Front') { // default it is set to Front     
        $this->userType = $arg;
    }
    //==== rest code will be as it is ====
    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $this->_identity=new UserIdentity($this->username,$this->password);
            $this->_identity->userType = $this->userType; // this will pass flag to the UserIdentity class
            if(!$this->_identity->authenticate())
                $this->addError('password','Incorrect username or password.');
        }
    }

UserIdentity:

Path: components/UserIdentity.php

Same like LoginForm, adding new member to the class.

<?php
class UserIdentity extends CUserIdentity
{   
    public $userType = 'Front';
 
    public function authenticate()
    {
        if($this->userType=='Front') // This is front login
        {
            // check if login details exists in database
                        $record=User::model()->findByAttributes(array('username'=>$this->username)); 
            if($record===null)
            { 
                $this->errorCode=self::ERROR_USERNAME_INVALID;
            }
            else if($record->password!==$this->password)            // here I compare db password with password field
            { 
                $this->errorCode=self::ERROR_PASSWORD_INVALID;
            }
            else
            {  
                $this->setState('userId',$record->userId);
                $this->setState('name', $record->firstName.' '.$record->lastName);
                $this->errorCode=self::ERROR_NONE;
            }
            return !$this->errorCode;
        }
        if($this->userType=='Back')// This is admin login
        {
            // check if login details exists in database
                        $record=AdminUser::model()->findByAttributes(array('email'=>$this->username));  // here I use Email as user name which comes from database
            if($record===null)
            { 
                $this->errorCode=self::ERROR_USERNAME_INVALID;
            }
            else if($record->password!==base64_encode($this->password)) // let we have base64_encode password in database
            { 
                $this->errorCode=self::ERROR_PASSWORD_INVALID;
            }
            else
            {  
                $this->setState('isAdmin',1);
                $this->setState('userId',$record->userId);
                $this->setState('name', $record->name);
                $this->errorCode=self::ERROR_NONE;
            }
            return !$this->errorCode;
        }
    }
}

Code in action:

Now all is set, we just need to use LoginForm object in controller files.

Path: Controllers/Front/SiteController.php

$model=new LoginForm('Front'); // Front side login form which will use 'User' module

Path: Controllers/Back/SiteController.php

$model=new LoginForm('Back'); // Admin side login form which will use 'AdminUser' module

You may also find some good articles on how to manage user access levels..etc. But as a beginner i tried this code, It may help you. Share your thoughts and comments.

Happy Coding! :)

Total 7 comments

#16340 report it
Selvakumar at 2014/02/12 09:29am
Two log-in in single form

Can i have two create front and back-end folders in Controller? please provide the syntax of controller and view ? If i want both log-in single form how can i do?

#11070 report it
aviral abijeet at 2012/12/14 01:55am
front

plz provide the source code of front controller and back controller

#9107 report it
vibhaJadwani at 2012/07/20 08:58am
$this->_id = $record->userId;

@redguy: Thanks for info.

#9105 report it
redguy at 2012/07/20 06:46am
$this->setState('userId',$record->userId);

You should rather use built in user id this way:

class UserIdentity extends CUserIdentity
{
   private $_id;
 
   public getId() {
      return $this->_id;
   }
 
   public function authenticate() {
      ...
      $this->_id = $record->userId; //when login is correct
      ...
   }

This way you can access it with Yii::app()->user->id

Without this code - Yii::app()->user->id will hold user login...

#9102 report it
kiran sharma at 2012/07/20 02:33am
reply @Session mixed

I just missed that, wroking now. +1 fot this.

#9100 report it
vibhaJadwani at 2012/07/20 02:28am
Session mixed

@kiran: Once you follow http://www.yiiframework.com/wiki/63/organize-directories-for-applications-with-front-end-and-back-end-using-webapplicationend-behavior then make sure you define name field in config/front.php & config/back.php file as shown below. Sorry i don't know the reason but once i have added both different name it solves session issue.

<?php
return CMap::mergeArray(
    require(dirname(__FILE__).'/main.php'),
    array(
        'name'=>'Website Admin',
    )
);
?>
#9099 report it
kiran sharma at 2012/07/20 02:17am
Frontend - Backend user overwrite on login

On following above structure it overwrite front/backend logged user.

Leave a comment

Please to leave your comment.

Write new article