Hi i\'m quite new to yii framework, currently trying to establish a login through database authentication. but while im trying to log in i get this error saying
You have to write your authentication logic inside UserIdentity class not in LoginForm model.
LoginForm model ex:-
public function authenticate($attribute, $params) {
if (!$this->hasErrors()) {
$this->_identity = new UserIdentity($this->email, $this->password);
if (!$this->_identity->authenticate())
$this->addError('password', 'Incorrect username or password.');
}
}
public function login() {
if ($this->_identity === null) {
$this->_identity = new UserIdentity($this->email, $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;
}
For database authentication you must have to add your authetication logic inside authenticate function using components\UserIdentity.php
public function authenticate() {
Yii::app()->getModule('auth')->getModule('user'); #import your module.
$record = User::model()
->findByAttributes(array('email' => CHtml::encode($this->email))); #database call
if ($record === null)
$this->errorCode = self::ERROR_USERNAME_INVALID;
#else if ($record->password !== crypt($this->password, $record->password))
else if ($record->password !== $this->password)
$this->errorCode = self::ERROR_PASSWORD_INVALID;
else {
$this->_uid = $record->user_id;
$this->setState('title', $record->user_name);
$this->setState('uid', $this->_uid);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
If you have role based login then you have to add WebUser class in config/main.php.
components' => array(
'user' => array(
// enable cookie-based authentication
'class' => 'WebUser',
'allowAutoLogin' => true,
'loginUrl'=>array('/site/login'),
'returnUrl'=>array('/site/index'),
),
}
For role based assess check you have to write components\WebUser.php Class -
class WebUser extends CWebUser {
public function checkAccess($operation, $params = array()) {
if (empty($this->id)) {
// Not identified => no rights
return false;
}
$role = $this->getState("roles");
if ($role === '3') {
return true; // super admin role has access to everything
}else if ($role === '1') {
return true; // admin(manager) role has access to everything
}
// allow access if the operation request is the current user's role
return ($operation === $role);
}
}
For more information check Authentication and Authorization