Create two table for example user and admin ¶
login links will be
youdomain.com/index.php?r=site/site/login
make a copy of site/login.php and name it as AdminLogin.php
youdomain.com/index.php?r=site/AdminLogin
CREATE TABLE IF NOT EXISTS `tbl_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL,
`password` varchar(128) NOT NULL,
`salt` varchar(128) NOT NULL,
`first_name` varchar(200) NOT NULL,
`last_name` varchar(200) NOT NULL,
`email` varchar(128) NOT NULL,
`profile` int(11) DEFAULT '0',
`photo` varchar(120) DEFAULT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `tbl_admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL,
`password` varchar(128) NOT NULL,
`salt` varchar(128) NOT NULL,
`first_name` varchar(200) NOT NULL,
`last_name` varchar(200) NOT NULL,
`email` varchar(128) NOT NULL,
`admin_name` varchar(128) NOT NULL,
`admin_type` varchar(128) NOT NULL,
`profile` int(11) DEFAULT '1',
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
While creating users make sure profile value should pass hidden value 1 for admin and 0 for user ¶
in controller/SiteController.php
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('index.php?r=user/dashboard');
}
// display the login form
$this->render('login',array('model'=>$model));
}
public function actionAdminLogin()
{
$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->login1())
if(Yii::app()->user->profile==1)
{
$this->redirect('index.php?r=admin/dashboard');
}
else{
$this->redirect('index.php?r=user/dashboard');
}
}
// display the login form
$this->render('login',array('model'=>$model));
}
on models/LoginForm.php
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.');
}
}
public function authenticate1($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);
if(!$this->_identity->authenticate())
$this->addError('password','Incorrect username or password.');
}
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;
}
public function login1()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate1())
$this->addError('password','Incorrect username or password.');
}
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;
}
components/UserIdentity.php
public function authenticate()
{
//$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
$user=User::model()->findByAttributes(array('username'=>strtolower($this->username),'status'=>1));
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->setState('profile', $user->profile);
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
public function authenticate1()
{
$user=Admin::model()->findByAttributes(array('username'=>strtolower($this->username),'status'=>1));
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->setState('profile', $user->profile);
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode==self::ERROR_NONE;
}
Thanks Balu
And now correct way
Create 2 different Identity classes: UserIdentity and OperatorIdentity extends CBaseUserIdentity. Implement authenticate(). Main idea of Identity - allow to authenticate from different sources. One source - one Identity. Don't make auauthenticate1(), authenticate2(), .. authenticateOver9000().
Create one more class AdminWebUser extends CWebUser. It can be empty class, but class name used for cookie name, so we can be logged in as user and as admin separately. Create in config file (main.php) new component "admin" with class => 'AdminWebUser'. Also can set any other options like cookie options. Now we can ask Yii::app()->user->isGuest and Yii::app()->admin->isGuest. If you don't need separate login - just skip this point.
Also, please, create LoginForm and AdminLoginForm. If both has lot of same code - use Inheritance!
Thankyou for your suggestion
I don't have deep knowledge, I had just created as on the way my project needed, This will works fine, I consider your points in my upcoming projects, Thank you bro...
Massive code duplication
This contains massive code duplication and will create issues when trying to do authentication per user/admin. I kinda agree with @Mikslr, his solution is quite more elegant (in the past I've been using exactly such implementation for small website). Still Yii is not designed to have multiple User Components in parallel and this deprives you of the ability to use RBAC.
Two log-in in single form
Could you please explain for two log-in in single form or in different URL. Please help me I'm struggled in this about a week.
Two or Mulit log-in in single form
see wiki - http://www.yiiframework.com/wiki/779/how-to-pass-the-third-parameter-to-useridentity-on-login-authentication/
accessRule
@Mikslr method is the best solution. However, it still dont work with Yii accessRule filter. the filter is hardcoded to call Yii::app()->getUser() so it will still default tto User but not admin in this case.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.