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-16 23:38:43 +08:00
|
|
|
private $_user;
|
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-16 23:38:43 +08:00
|
|
|
$user = $this->getUserByUsername($this->username);
|
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-16 23:38:43 +08:00
|
|
|
$user = $this->getUserByUsername($this->username);
|
2013-11-17 02:16:10 +08:00
|
|
|
return Yii::$app->user->login($user, $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
|
|
|
|
|
|
|
/**
|
|
|
|
* Finds user by username
|
|
|
|
*
|
|
|
|
* @param string $username
|
|
|
|
* @return User|null
|
|
|
|
*/
|
|
|
|
private function getUserByUsername($username)
|
|
|
|
{
|
|
|
|
if ($this->_user === null) {
|
|
|
|
$this->_user = User::findByUsername($username);
|
|
|
|
}
|
|
|
|
return $this->_user;
|
|
|
|
}
|
2013-05-24 22:14:49 +08:00
|
|
|
}
|