yii2-netdisk/models/LoginForm.php

75 lines
1.4 KiB
PHP
Raw Normal View History

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
[['username', 'password'], 'required'],
2013-05-24 22:14:49 +08:00
// rememberMe must be a boolean value
2013-11-13 17:41:25 +08:00
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
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()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
2013-05-24 22:14:49 +08:00
}
}
/**
* 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-17 09:39:51 +08:00
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
2013-11-17 09:39:51 +08:00
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
2013-11-17 09:39:51 +08:00
return $this->_user;
}
2013-05-24 22:14:49 +08:00
}