2013-05-24 22:14:49 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace app\models;
|
|
|
|
|
|
|
|
use Yii;
|
|
|
|
use yii\base\Model;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* LoginForm is the model behind the login form.
|
|
|
|
*/
|
|
|
|
class LoginForm extends Model
|
|
|
|
{
|
|
|
|
public $username;
|
|
|
|
public $password;
|
|
|
|
public $rememberMe = true;
|
2013-11-17 09:39:51 +08:00
|
|
|
|
|
|
|
private $_user = false;
|
2013-05-24 22:14:49 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @return array the validation rules.
|
|
|
|
*/
|
|
|
|
public function rules()
|
|
|
|
{
|
2013-10-18 17:48:27 +08:00
|
|
|
return [
|
2013-05-24 22:14:49 +08:00
|
|
|
// username and password are both required
|
2013-11-12 22:39:23 +08:00
|
|
|
[['username', 'password'], 'required'],
|
2013-05-24 22:14:49 +08:00
|
|
|
// password is validated by validatePassword()
|
2013-11-13 17:41:25 +08:00
|
|
|
['password', 'validatePassword'],
|
2013-05-24 22:14:49 +08:00
|
|
|
// rememberMe must be a boolean value
|
2013-11-13 17:41:25 +08:00
|
|
|
['rememberMe', 'boolean'],
|
2013-10-18 17:48:27 +08:00
|
|
|
];
|
2013-05-24 22:14:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Validates the password.
|
|
|
|
* This method serves as the inline validation for password.
|
|
|
|
*/
|
|
|
|
public function validatePassword()
|
|
|
|
{
|
2013-11-17 09:39:51 +08:00
|
|
|
$user = $this->getUser();
|
2013-05-24 22:14:49 +08:00
|
|
|
if (!$user || !$user->validatePassword($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()) {
|
2013-11-17 09:39:51 +08:00
|
|
|
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
|
2013-05-24 22:14:49 +08:00
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2013-11-16 23:38:43 +08:00
|
|
|
|
|
|
|
/**
|
2013-11-17 09:39:51 +08:00
|
|
|
* Finds user by [[username]]
|
2013-11-16 23:38:43 +08:00
|
|
|
*
|
|
|
|
* @return User|null
|
|
|
|
*/
|
2013-11-17 09:39:51 +08:00
|
|
|
private function getUser()
|
2013-11-16 23:38:43 +08:00
|
|
|
{
|
2013-11-17 09:39:51 +08:00
|
|
|
if ($this->_user === false) {
|
|
|
|
$this->_user = User::findByUsername($this->username);
|
2013-11-16 23:38:43 +08:00
|
|
|
}
|
2013-11-17 09:39:51 +08:00
|
|
|
return $this->_user;
|
2013-11-16 23:38:43 +08:00
|
|
|
}
|
2013-05-24 22:14:49 +08:00
|
|
|
}
|