3f2bc3d0
Administrator
first commit
|
1
|
<?php
|
550eac02
Administrator
second
|
2
|
|
3f2bc3d0
Administrator
first commit
|
3
4
5
6
7
8
|
namespace common\models;
use Yii;
use yii\base\Model;
/**
|
550eac02
Administrator
second
|
9
|
* LoginForm is the model behind the login form.
|
3f2bc3d0
Administrator
first commit
|
10
11
12
|
*/
class LoginForm extends Model
{
|
550eac02
Administrator
second
|
13
|
public $username;
|
3f2bc3d0
Administrator
first commit
|
14
|
public $password;
|
550eac02
Administrator
second
|
15
|
public $rememberMe;
|
3f2bc3d0
Administrator
first commit
|
16
|
|
550eac02
Administrator
second
|
17
|
private $_user = false;
|
3f2bc3d0
Administrator
first commit
|
18
19
20
|
/**
|
550eac02
Administrator
second
|
21
|
* @return array the validation rules.
|
3f2bc3d0
Administrator
first commit
|
22
23
24
25
26
|
*/
public function rules()
{
return [
// username and password are both required
|
550eac02
Administrator
second
|
27
|
[['username', 'password'], 'required'],
|
3f2bc3d0
Administrator
first commit
|
28
29
30
31
32
33
34
|
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
|
550eac02
Administrator
second
|
35
36
37
38
39
40
41
42
43
|
public function attributeLabels()
{
return [
'username'=>'Логин',
'password'=>'Пароль',
'rememberMe'=>'Запомнить',
];
}
|
3f2bc3d0
Administrator
first commit
|
44
45
46
47
48
49
50
51
52
53
54
|
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
|
550eac02
Administrator
second
|
55
|
|
3f2bc3d0
Administrator
first commit
|
56
57
58
59
60
61
62
63
|
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
|
3f2bc3d0
Administrator
first commit
|
64
65
66
67
68
|
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
|
550eac02
Administrator
second
|
69
|
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
|
3f2bc3d0
Administrator
first commit
|
70
71
72
73
74
75
76
77
78
79
|
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
|
550eac02
Administrator
second
|
80
|
public function getUser()
|
3f2bc3d0
Administrator
first commit
|
81
|
{
|
550eac02
Administrator
second
|
82
83
|
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
|
3f2bc3d0
Administrator
first commit
|
84
85
86
87
|
}
return $this->_user;
}
|
3f2bc3d0
Administrator
first commit
|
88
|
}
|