1 | <?php |
||
2 | namespace common\models; |
||
3 | |||
4 | use Yii; |
||
5 | use yii\base\Model; |
||
6 | |||
7 | /** |
||
8 | * Login form |
||
9 | */ |
||
10 | class LoginForm extends Model |
||
11 | { |
||
12 | public $email; |
||
13 | public $password; |
||
14 | public $rememberMe = true; |
||
15 | |||
16 | private $user = false; |
||
17 | private $tmp_user; |
||
18 | |||
19 | public function __construct(\common\interfaces\UserInterface $user, $config = []) { |
||
20 | $this->tmp_user = $user; |
||
21 | parent::__construct($config); |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * @inheritdoc |
||
26 | */ |
||
27 | public function rules() |
||
28 | { |
||
29 | return [ |
||
30 | // email and password are both required |
||
31 | ['email', 'filter', 'filter' => 'trim'], |
||
32 | ['email', 'filter', 'filter' => 'strtolower'], |
||
33 | [['email', 'password'], 'required'], |
||
34 | ['email', 'email'], |
||
35 | // rememberMe must be a boolean value |
||
36 | ['rememberMe', 'boolean'], |
||
37 | // password is validated by validatePassword() |
||
38 | ['password', 'validatePassword'], |
||
39 | ]; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Validates the password. |
||
44 | * This method serves as the inline validation for password. |
||
45 | */ |
||
46 | public function validatePassword() |
||
47 | { |
||
48 | if (!$this->hasErrors()) { |
||
49 | $user = $this->getUser(); |
||
50 | if (!$user || !$user->validatePassword($this->password)) { |
||
51 | $this->addError('password', 'Incorrect email or password.'); |
||
52 | } |
||
53 | } |
||
54 | } |
||
55 | |||
56 | /** |
||
57 | * Logs in a user using the provided email and password. |
||
58 | * |
||
59 | * @return boolean whether the user is logged in successfully |
||
60 | */ |
||
61 | public function login() |
||
62 | { |
||
63 | if($this->validate()) { |
||
64 | $user = $this->getUser(); |
||
65 | if($user->isVerified()) { |
||
66 | return Yii::$app->user->login($user, $this->rememberMe ? 3600 * 24 * 30 : 0); |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
67 | } else { |
||
68 | Yii::$app->session->setFlash('warning', 'You must verify your account before you can proceed. Please check your email inbox for a verification email and follow the instructions.'); |
||
69 | } |
||
70 | } |
||
71 | return false; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * Finds user by [[email]] |
||
76 | * |
||
77 | * @return User|null |
||
78 | */ |
||
79 | public function getUser() |
||
80 | { |
||
81 | if ($this->user === false) { |
||
82 | $this->user = $this->tmp_user->findByEmail($this->email); |
||
83 | } |
||
84 | |||
85 | return $this->user; |
||
86 | } |
||
87 | } |
||
88 |