Hi, i would like to authenticate my user using my existing table. I have created the Model Employee.
model/Employee.php
under Employee model, i have added this.
public function getId()
{
return $this->EmployeeID;
}
public static function findByUsername($username)
{
return static::findOne(['EmployeeID' => $username]);
}
public function validatePassword($employeeID,$password)
{
return static::findBySql('select * from employee where `EmployeeID` = "'.$employeeID.'" AND `Password` = PASSWORD("'.$password.'")')->exists();
}
And i create my custom login form.
\common\models\CustomLoginForm
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class CustomLoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($user->EmployeeID,$this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate())
{
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Employee::findByUsername($this->username);
}
return $this->_user;
}
}
And i have change the ‘user’ under component in backend config like below:
'user' => [
'identityClass' => 'common\models\Employee',
'enableAutoLogin' => true,
],
When i key in the wrong password, it shows failed login message, however if i key in the right password, nothing is happen and it go back to the login screen without any error message. Is there something else that im missing here? Is it the session is not registered correct?
Please help, thanks.