LoginForm   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 156
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 82.98%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 8
dl 0
loc 156
ccs 39
cts 47
cp 0.8298
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A attributeLabels() 0 9 1
B rules() 0 53 10
A login() 0 10 3
A beforeValidate() 0 10 2
A getUser() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Form;
13
14
use Da\User\Helper\SecurityHelper;
15
use Da\User\Model\User;
16
use Da\User\Query\UserQuery;
17
use Da\User\Traits\ModuleAwareTrait;
18
use Da\User\Validator\TwoFactorCodeValidator;
19
use Yii;
20
use yii\base\InvalidParamException;
21
use yii\base\Model;
22
23
class LoginForm extends Model
24
{
25
    use ModuleAwareTrait;
26
27
    /**
28
     * @var string login User's email or username
29
     */
30
    public $login;
31
    /**
32
     * @var string User's password
33
     */
34
    public $password;
35
    /**
36
     * @var string User's two-factor authentication code
37
     */
38
    public $twoFactorAuthenticationCode;
39
    /**
40
     * @var bool whether to remember User's login
41
     */
42
    public $rememberMe = false;
43
    /**
44
     * @var User
45
     */
46
    protected $user;
47
    /**
48
     * @var UserQuery
49
     */
50
    protected $query;
51
    /**
52
     * @var SecurityHelper
53
     */
54
    protected $securityHelper;
55
56
    /**
57
     * @param UserQuery      $query
58
     * @param SecurityHelper $securityHelper
59
     * @param array          $config
60
     */
61 4
    public function __construct(UserQuery $query, SecurityHelper $securityHelper, $config = [])
62
    {
63 4
        $this->query = $query;
64 4
        $this->securityHelper = $securityHelper;
65 4
        parent::__construct($config);
66 4
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 4
    public function attributeLabels()
72
    {
73
        return [
74 4
            'login' => Yii::t('usuario', 'Login'),
75 4
            'password' => Yii::t('usuario', 'Password'),
76 4
            'rememberMe' => Yii::t('usuario', 'Remember me next time'),
77 4
            'twoFactorAuthenticationCode' => Yii::t('usuario', 'Two factor authentication code')
78
        ];
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     *
84
     * @throws \Da\TwoFA\Exception\InvalidSecretKeyException (only if package is being used)
85
     */
86 4
    public function rules()
87
    {
88
        return [
89 4
            'requiredFields' => [['login', 'password'], 'required'],
90
            'requiredFieldsTwoFactor' => [
91
                ['login', 'password', 'twoFactorAuthenticationCode'],
92
                'required',
93
                'on' => '2fa'
94
            ],
95
            'loginTrim' => ['login', 'trim'],
96
            'twoFactorAuthenticationCodeTrim' => ['twoFactorAuthenticationCode', 'trim'],
97
            'passwordValidate' => [
98 4
                'password',
99
                function ($attribute) {
100 4
                    if ($this->user === null ||
101 4
                        !$this->securityHelper->validatePassword($this->password, $this->user->password_hash)
102
                    ) {
103 3
                        $this->addError($attribute, Yii::t('usuario', 'Invalid login or password'));
104
                    }
105 4
                },
106
            ],
107
            'twoFactorAuthenticationCodeValidate' => [
108 4
                'twoFactorAuthenticationCode',
109
                function ($attribute) {
110
                    if ($this->user === null ||
111
                        !(new TwoFactorCodeValidator(
112
                            $this->user,
113
                            $this->twoFactorAuthenticationCode,
114
                            $this->module->twoFactorAuthenticationCycles
115
                        ))
116
                            ->validate()) {
117
                        $this->addError($attribute, Yii::t('usuario', 'Invalid two factor authentication code'));
118
                    }
119 4
                }
120
            ],
121
            'confirmationValidate' => [
122 4
                'login',
123
                function ($attribute) {
124 4
                    if ($this->user !== null) {
125 4
                        $module = $this->getModule();
126 4
                        $confirmationRequired = $module->enableEmailConfirmation && !$module->allowUnconfirmedEmailLogin;
127 4
                        if ($confirmationRequired && !$this->user->getIsConfirmed()) {
128 1
                            $this->addError($attribute, Yii::t('usuario', 'You need to confirm your email address'));
129
                        }
130 4
                        if ($this->user->getIsBlocked()) {
131 1
                            $this->addError($attribute, Yii::t('usuario', 'Your account has been blocked'));
132
                        }
133
                    }
134 4
                },
135
            ],
136
            'rememberMe' => ['rememberMe', 'boolean'],
137
        ];
138
    }
139
140
    /**
141
     * Validates form and logs the user in.
142
     *
143
     * @throws InvalidParamException
144
     * @return bool                  whether the user is logged in successfully
145
     */
146 4
    public function login()
147
    {
148 4
        if ($this->validate()) {
149 4
            $duration = $this->rememberMe ? $this->module->rememberLoginLifespan : 0;
150
151 4
            return Yii::$app->getUser()->login($this->user, $duration);
0 ignored issues
show
Bug introduced by
The method getUser does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
152
        }
153
154 3
        return false;
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160 4
    public function beforeValidate()
161
    {
162 4
        if (parent::beforeValidate()) {
163 4
            $this->user = $this->query->whereUsernameOrEmail(trim($this->login))->one();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->query->whereUsern...m($this->login))->one() can also be of type object<yii\db\ActiveRecord> or array. However, the property $user is declared as type object<Da\User\Model\User>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
164
165 4
            return true;
166
        }
167
168
        return false;
169
    }
170
171
    /**
172
     * @return User
173
     */
174 4
    public function getUser()
175
    {
176 4
        return $this->user;
177
    }
178
}
179