Login::rules()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace yrc\forms;
4
5
use yii\web\UnauthorizedHttpException;
6
use Yii;
7
8
/**
9
 * @class Login
10
 * Form for authenticating users
11
 */
12
abstract class Login extends \yii\base\Model
13
{
14
    /**
15
     * The user's email
16
     * @var string
17
     */
18
    public $email;
19
20
    /**
21
     * The user's password
22
     * @var string
23
     */
24
    public $password;
25
26
    /**
27
     * The users OTP code, if provided
28
     * @var string
29
     */
30
    public $otp;
31
32
    /**
33
     * The user object
34
     * @var User
0 ignored issues
show
Bug introduced by
The type yrc\forms\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
     */
36
    private $user = null;
37
38
    /**
39
     * The login status code
40
     * @var int $exitStatus
41
     */
42
    private $exitStatus = 0;
43
44
    /**
45
     * Retrieves the exit status generated by the validator
46
     * @return integer
47
     */
48
    public function getExitStatus()
49
    {
50
        return $this->exitStatus;
51
    }
52
53
    /**
54
     * Yii2 model validation rules
55
     * @return array
56
     */
57
    public function rules()
58
    {
59
        return [
60
            [['email', 'password'], 'required'],
61
            [['email'], 'email'],
62
            [['email', 'password'], 'string', 'max' => 255],
63
            [['otp'], 'string', 'length' => 6],
64
            [['password'], 'string', 'min' => 8],
65
            [['password'], 'validatePasswordAndOTP'],
66
        ];
67
    }
68
69
    /**
70
     * Retreives the user object
71
     * @return User
72
     */
73
    public function getUser()
74
    {
75
        if ($this->user !== null) {
76
            return $this->user;
77
        }
78
        
79
        // We only allow verified users to authenticate
80
        if ($this->user === null) {
81
            $this->user = Yii::$app->user->identityClass::findOne(['email' => $this->email, 'verified' => 1]);
82
        }
83
84
        return $this->user;
85
    }
86
87
    /**
88
     * Validates the users' password and OTP code
89
     * @param array $attribute
90
     * @param array $params
91
     */
92
    public function validatePasswordAndOTP($attribute, $params)
0 ignored issues
show
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

92
    public function validatePasswordAndOTP($attribute, /** @scrutinizer ignore-unused */ $params)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
93
    {
94
        // Only proceed if the preceeding validation rules passed
95
        if (!$this->hasErrors()) {
96
            // Fetch the user object
97
            $user = $this->getUser();
98
99
            // If the user is null or false, an error occured when fetching them, thus throw an error
100
            if (!$user) {
0 ignored issues
show
introduced by
$user is of type yrc\forms\User, thus it always evaluated to true.
Loading history...
101
                $this->addError($attribute, Yii::t('yrc', 'Incorrect email address or password.'));
102
            } else {
103
                // If the password doesn't validate, throw an error
104
                if (!$user->validatePassword($this->password)) {
105
                    $this->addError($attribute, Yii::t('yrc', 'Incorrect email address or password.'));
0 ignored issues
show
Bug introduced by
$attribute of type array is incompatible with the type string expected by parameter $attribute of yii\base\Model::addError(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

105
                    $this->addError(/** @scrutinizer ignore-type */ $attribute, Yii::t('yrc', 'Incorrect email address or password.'));
Loading history...
106
                }
107
108
                // If the user requires an OTP code, but it wasn't provided, throw a special HTTP status code
109
                if ($user->isOTPEnabled() && $this->otp === null) {
110
                    $this->addError('otp', Yii::t('yrc', 'Two factor authentication is enabled for this account.'));
111
                    $this->exitStatus = 1;
112
                }
113
114
                // Check the OTP code if it is enabled for the account
115
                if ($user->isOTPEnabled() === true) {
116
                    // Verify the OTP code is valid
117
                    if ($user->verifyOTP((string)$this->otp) === false) {
118
                        $this->addError($attribute, Yii::t('yrc', 'Incorrect email address or password.'));
119
                    }
120
                }
121
            }
122
        }
123
    }
124
125
    /**
126
     * Authenticates the user by running the validators, and returning generate auth token
127
     * @return bool
128
     */
129
    public function authenticate()
130
    {
131
        if ($this->validate()) {
132
            $tokenClass = (Yii::$app->user->identityClass::TOKEN_CLASS);
133
            $token = $tokenClass::generate($this->getUser()->id);
134
135
            // Actually log the user into the application so we can access global user state
136
            Yii::$app->user->loginByAccessToken($token);
0 ignored issues
show
Bug introduced by
The method loginByAccessToken() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

136
            Yii::$app->user->/** @scrutinizer ignore-call */ 
137
                             loginByAccessToken($token);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
137
            return $token;
138
        }
139
140
        return false;
141
    }
142
}
143