yii2-netdisk/models/LoginForm.php

82 lines
1.9 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.
2016-04-29 00:06:20 +08:00
*
2021-12-30 15:59:54 +08:00
* @property-read User|null $user
2016-04-29 00:06:20 +08:00
*
2013-05-24 22:14:49 +08:00
*/
class LoginForm extends Model
{
2014-03-16 12:46:16 +08:00
public $username;
public $password;
public $rememberMe = true;
2013-11-17 09:39:51 +08:00
2014-03-16 12:46:16 +08:00
private $_user = false;
2013-05-24 22:14:49 +08:00
2014-10-25 21:28:36 +08:00
2014-03-16 12:46:16 +08:00
/**
* @return array the validation rules.
*/
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'],
];
}
2013-05-24 22:14:49 +08:00
2014-03-16 12:46:16 +08:00
/**
* Validates the password.
* This method serves as the inline validation for password.
2014-07-31 14:11:55 +08:00
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
2014-03-16 12:46:16 +08:00
*/
2014-07-31 14:11:55 +08:00
public function validatePassword($attribute, $params)
2014-03-16 12:46:16 +08:00
{
if (!$this->hasErrors()) {
$user = $this->getUser();
2014-03-16 12:46:16 +08:00
if (!$user || !$user->validatePassword($this->password)) {
2014-07-31 14:11:55 +08:00
$this->addError($attribute, 'Incorrect username or password.');
2014-03-16 12:46:16 +08:00
}
}
}
2013-05-24 22:14:49 +08:00
2014-03-16 12:46:16 +08:00
/**
* Logs in a user using the provided username and password.
2016-10-20 20:10:38 +08:00
* @return bool whether the user is logged in successfully
2014-03-16 12:46:16 +08:00
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
2015-06-05 22:40:49 +08:00
return false;
2014-03-16 12:46:16 +08:00
}
2014-03-16 12:46:16 +08:00
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
2013-05-24 22:14:49 +08:00
}