GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( ecf3ef...78a151 )
by Robert
11:40
created

User::getIdentity()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.1308

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 11
cts 13
cp 0.8462
rs 8.7624
c 0
b 0
f 0
cc 6
eloc 15
nc 5
nop 1
crap 6.1308
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidValueException;
14
use yii\rbac\CheckAccessInterface;
15
16
/**
17
 * User is the class for the `user` application component that manages the user authentication status.
18
 *
19
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
20
 * If the user is a guest, the [[identity]] property would return `null`. Otherwise, it would
21
 * be an instance of [[IdentityInterface]].
22
 *
23
 * You may call various methods to change the user authentication status:
24
 *
25
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
26
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
27
 * - [[setIdentity()]]: changes the user identity without touching session or cookie
28
 *   (this is best used in stateless RESTful API implementation).
29
 *
30
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
31
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
32
 * You are also required to set [[identityClass]] with the name of this class.
33
 *
34
 * User is configured as an application component in [[\yii\web\Application]] by default.
35
 * You can access that instance via `Yii::$app->user`.
36
 *
37
 * You can modify its configuration by adding an array to your application config under `components`
38
 * as it is shown in the following example:
39
 *
40
 * ```php
41
 * 'user' => [
42
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
43
 *     'enableAutoLogin' => true,
44
 *     // 'loginUrl' => ['user/login'],
45
 *     // ...
46
 * ]
47
 * ```
48
 *
49
 * @property string|int $id The unique identifier for the user. If `null`, it means the user is a guest. This
50
 * property is read-only.
51
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
52
 * user. `null` is returned if the user is not logged in (not authenticated).
53
 * @property bool $isGuest Whether the current user is a guest. This property is read-only.
54
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
55
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
56
 *
57
 * @author Qiang Xue <[email protected]>
58
 * @since 2.0
59
 */
60
class User extends Component
61
{
62
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
63
    const EVENT_AFTER_LOGIN = 'afterLogin';
64
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
65
    const EVENT_AFTER_LOGOUT = 'afterLogout';
66
67
    /**
68
     * @var string the class name of the [[identity]] object.
69
     */
70
    public $identityClass;
71
    /**
72
     * @var bool whether to enable cookie-based login. Defaults to `false`.
73
     * Note that this property will be ignored if [[enableSession]] is `false`.
74
     */
75
    public $enableAutoLogin = false;
76
    /**
77
     * @var bool whether to use session to persist authentication status across multiple requests.
78
     * You set this property to be `false` if your application is stateless, which is often the case
79
     * for RESTful APIs.
80
     */
81
    public $enableSession = true;
82
    /**
83
     * @var string|array the URL for login when [[loginRequired()]] is called.
84
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
85
     * The first element of the array should be the route to the login action, and the rest of
86
     * the name-value pairs are GET parameters used to construct the login URL. For example,
87
     *
88
     * ```php
89
     * ['site/login', 'ref' => 1]
90
     * ```
91
     *
92
     * If this property is `null`, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
93
     */
94
    public $loginUrl = ['site/login'];
95
    /**
96
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is `true`.
97
     * @see Cookie
98
     */
99
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
100
    /**
101
     * @var int the number of seconds in which the user will be logged out automatically if he
102
     * remains inactive. If this property is not set, the user will be logged out after
103
     * the current session expires (c.f. [[Session::timeout]]).
104
     * Note that this will not work if [[enableAutoLogin]] is `true`.
105
     */
106
    public $authTimeout;
107
    /**
108
     * @var CheckAccessInterface The access checker to use for checking access.
109
     * If not set the application auth manager will be used.
110
     * @since 2.0.9
111
     */
112
    public $accessChecker;
113
    /**
114
     * @var int the number of seconds in which the user will be logged out automatically
115
     * regardless of activity.
116
     * Note that this will not work if [[enableAutoLogin]] is `true`.
117
     */
118
    public $absoluteAuthTimeout;
119
    /**
120
     * @var bool whether to automatically renew the identity cookie each time a page is requested.
121
     * This property is effective only when [[enableAutoLogin]] is `true`.
122
     * When this is `false`, the identity cookie will expire after the specified duration since the user
123
     * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration
124
     * since the user visits the site the last time.
125
     * @see enableAutoLogin
126
     */
127
    public $autoRenewCookie = true;
128
    /**
129
     * @var string the session variable name used to store the value of [[id]].
130
     */
131
    public $idParam = '__id';
132
    /**
133
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
134
     * This is used when [[authTimeout]] is set.
135
     */
136
    public $authTimeoutParam = '__expire';
137
    /**
138
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
139
     * This is used when [[absoluteAuthTimeout]] is set.
140
     */
141
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
142
    /**
143
     * @var string the session variable name used to store the value of [[returnUrl]].
144
     */
145
    public $returnUrlParam = '__returnUrl';
146
    /**
147
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
148
     * @since 2.0.8
149
     */
150
    public $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
151
152
    private $_access = [];
153
154
155
    /**
156
     * Initializes the application component.
157
     */
158 85
    public function init()
159
    {
160 85
        parent::init();
161
162 85
        if ($this->identityClass === null) {
163
            throw new InvalidConfigException('User::identityClass must be set.');
164
        }
165 85
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
166
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
167
        }
168 85
        if (!empty($this->accessChecker) && is_string($this->accessChecker)) {
169 1
            $this->accessChecker = Yii::createObject($this->accessChecker);
170
        }
171 85
    }
172
173
    private $_identity = false;
174
175
    /**
176
     * Returns the identity object associated with the currently logged-in user.
177
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
178
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
179
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
180
     * This is only useful when [[enableSession]] is true.
181
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
182
     * `null` is returned if the user is not logged in (not authenticated).
183
     * @see login()
184
     * @see logout()
185
     */
186 76
    public function getIdentity($autoRenew = true)
187
    {
188 76
        if ($this->_identity === false) {
189 24
            if ($this->enableSession && $autoRenew) {
190
                try {
191 23
                    $this->_identity = null;
192 23
                    $this->renewAuthStatus();
193 1
                } catch (\Exception $e) {
194 1
                    $this->_identity = false;
195 1
                    throw $e;
196
                } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
197
                    $this->_identity = false;
198 22
                    throw $e;
199
                }
200
            } else {
201 1
                return null;
202
            }
203
        }
204
205 74
        return $this->_identity;
206
    }
207
208
    /**
209
     * Sets the user identity object.
210
     *
211
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
212
     * to change the identity of the current user.
213
     *
214
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
215
     * If null, it means the current user will be a guest without any associated identity.
216
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
217
     */
218 74
    public function setIdentity($identity)
219
    {
220 74
        if ($identity instanceof IdentityInterface) {
221 48
            $this->_identity = $identity;
0 ignored issues
show
Documentation Bug introduced by
It seems like $identity of type object<yii\web\IdentityInterface> is incompatible with the declared type boolean of property $_identity.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
222 48
            $this->_access = [];
223 29
        } elseif ($identity === null) {
224 29
            $this->_identity = null;
225
        } else {
226
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
227
        }
228 74
    }
229
230
    /**
231
     * Logs in a user.
232
     *
233
     * After logging in a user:
234
     * - the user's identity information is obtainable from the [[identity]] property
235
     *
236
     * If [[enableSession]] is `true`:
237
     * - the identity information will be stored in session and be available in the next requests
238
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
239
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
240
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
241
     *
242
     * If [[enableSession]] is `false`:
243
     * - the `$duration` parameter will be ignored
244
     *
245
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
246
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
247
     * @return bool whether the user is logged in
248
     */
249 30
    public function login(IdentityInterface $identity, $duration = 0)
250
    {
251 30
        if ($this->beforeLogin($identity, false, $duration)) {
252 30
            $this->switchIdentity($identity, $duration);
253 30
            $id = $identity->getId();
254 30
            $ip = Yii::$app->getRequest()->getUserIP();
255 30
            if ($this->enableSession) {
256 30
                $log = "User '$id' logged in from $ip with duration $duration.";
257
            } else {
258
                $log = "User '$id' logged in from $ip. Session not enabled.";
259
            }
260 30
            Yii::info($log, __METHOD__);
261 30
            $this->afterLogin($identity, false, $duration);
262
        }
263
264 30
        return !$this->getIsGuest();
265
    }
266
267
    /**
268
     * Logs in a user by the given access token.
269
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
270
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
271
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
272
     * @param string $token the access token
273
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
274
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
275
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
276
     * the access token is invalid or [[login()]] is unsuccessful.
277
     */
278 42
    public function loginByAccessToken($token, $type = null)
279
    {
280
        /* @var $class IdentityInterface */
281 42
        $class = $this->identityClass;
282 42
        $identity = $class::findIdentityByAccessToken($token, $type);
283 42
        if ($identity && $this->login($identity)) {
284 27
            return $identity;
285
        }
286
287 15
        return null;
288
    }
289
290
    /**
291
     * Logs in a user by cookie.
292
     *
293
     * This method attempts to log in a user using the ID and authKey information
294
     * provided by the [[identityCookie|identity cookie]].
295
     */
296 2
    protected function loginByCookie()
297
    {
298 2
        $data = $this->getIdentityAndDurationFromCookie();
299 2
        if (isset($data['identity'], $data['duration'])) {
300 1
            $identity = $data['identity'];
301 1
            $duration = $data['duration'];
302 1
            if ($this->beforeLogin($identity, true, $duration)) {
303 1
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
304 1
                $id = $identity->getId();
305 1
                $ip = Yii::$app->getRequest()->getUserIP();
306 1
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
307 1
                $this->afterLogin($identity, true, $duration);
308
            }
309
        }
310 2
    }
311
312
    /**
313
     * Logs out the current user.
314
     * This will remove authentication-related session data.
315
     * If `$destroySession` is true, all session data will be removed.
316
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
317
     * This parameter is ignored if [[enableSession]] is false.
318
     * @return bool whether the user is logged out
319
     */
320
    public function logout($destroySession = true)
321
    {
322
        $identity = $this->getIdentity();
323
        if ($identity !== null && $this->beforeLogout($identity)) {
0 ignored issues
show
Documentation introduced by
$identity is of type boolean, but the function expects a object<yii\web\IdentityInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
324
            $this->switchIdentity(null);
325
            $id = $identity->getId();
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $identity (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
326
            $ip = Yii::$app->getRequest()->getUserIP();
327
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
328
            if ($destroySession && $this->enableSession) {
329
                Yii::$app->getSession()->destroy();
0 ignored issues
show
Bug introduced by
The method getSession 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...
330
            }
331
            $this->afterLogout($identity);
0 ignored issues
show
Documentation introduced by
$identity is of type boolean, but the function expects a object<yii\web\IdentityInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
332
        }
333
334
        return $this->getIsGuest();
335
    }
336
337
    /**
338
     * Returns a value indicating whether the user is a guest (not authenticated).
339
     * @return bool whether the current user is a guest.
340
     * @see getIdentity()
341
     */
342 31
    public function getIsGuest()
343
    {
344 31
        return $this->getIdentity() === null;
345
    }
346
347
    /**
348
     * Returns a value that uniquely represents the user.
349
     * @return string|int the unique identifier for the user. If `null`, it means the user is a guest.
350
     * @see getIdentity()
351
     */
352 71
    public function getId()
353
    {
354 71
        $identity = $this->getIdentity();
355
356 71
        return $identity !== null ? $identity->getId() : null;
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $identity (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
357
    }
358
359
    /**
360
     * Returns the URL that the browser should be redirected to after successful login.
361
     *
362
     * This method reads the return URL from the session. It is usually used by the login action which
363
     * may call this method to redirect the browser to where it goes after successful authentication.
364
     *
365
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
366
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
367
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
368
     * @return string the URL that the user should be redirected to after login.
369
     * @see loginRequired()
370
     */
371 2
    public function getReturnUrl($defaultUrl = null)
372
    {
373 2
        $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
0 ignored issues
show
Bug introduced by
The method getSession 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...
374 2
        if (is_array($url)) {
375
            if (isset($url[0])) {
376
                return Yii::$app->getUrlManager()->createUrl($url);
377
            }
378
379
            $url = null;
380
        }
381
382 2
        return $url === null ? Yii::$app->getHomeUrl() : $url;
0 ignored issues
show
Bug introduced by
The method getHomeUrl 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...
383
    }
384
385
    /**
386
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
387
     * @param string|array $url the URL that the user should be redirected to after login.
388
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
389
     * The first element of the array should be the route, and the rest of
390
     * the name-value pairs are GET parameters used to construct the URL. For example,
391
     *
392
     * ```php
393
     * ['admin/index', 'ref' => 1]
394
     * ```
395
     */
396 2
    public function setReturnUrl($url)
397
    {
398 2
        Yii::$app->getSession()->set($this->returnUrlParam, $url);
0 ignored issues
show
Bug introduced by
The method getSession 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...
399 2
    }
400
401
    /**
402
     * Redirects the user browser to the login page.
403
     *
404
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
405
     * the user browser may be redirected back to the current page after successful login.
406
     *
407
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
408
     * calling this method.
409
     *
410
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
411
     *
412
     * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
413
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
414
     * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
415
     * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
416
     * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
417
     * @return Response the redirection response if [[loginUrl]] is set
418
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
419
     * not applicable.
420
     */
421 2
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
422
    {
423 2
        $request = Yii::$app->getRequest();
424 2
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
425 2
        if ($this->enableSession
426 2
            && $request->getIsGet()
427 2
            && (!$checkAjax || !$request->getIsAjax())
428 2
            && $canRedirect
429
        ) {
430 1
            $this->setReturnUrl($request->getUrl());
431
        }
432 2
        if ($this->loginUrl !== null && $canRedirect) {
433 1
            $loginUrl = (array) $this->loginUrl;
434 1
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
435 1
                return Yii::$app->getResponse()->redirect($this->loginUrl);
436
            }
437
        }
438 2
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
439
    }
440
441
    /**
442
     * This method is called before logging in a user.
443
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
444
     * If you override this method, make sure you call the parent implementation
445
     * so that the event is triggered.
446
     * @param IdentityInterface $identity the user identity information
447
     * @param bool $cookieBased whether the login is cookie-based
448
     * @param int $duration number of seconds that the user can remain in logged-in status.
449
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
450
     * @return bool whether the user should continue to be logged in
451
     */
452 30
    protected function beforeLogin($identity, $cookieBased, $duration)
453
    {
454 30
        $event = new UserEvent([
455 30
            'identity' => $identity,
456 30
            'cookieBased' => $cookieBased,
457 30
            'duration' => $duration,
458
        ]);
459 30
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
460
461 30
        return $event->isValid;
462
    }
463
464
    /**
465
     * This method is called after the user is successfully logged in.
466
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
467
     * If you override this method, make sure you call the parent implementation
468
     * so that the event is triggered.
469
     * @param IdentityInterface $identity the user identity information
470
     * @param bool $cookieBased whether the login is cookie-based
471
     * @param int $duration number of seconds that the user can remain in logged-in status.
472
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
473
     */
474 30
    protected function afterLogin($identity, $cookieBased, $duration)
475
    {
476 30
        $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
477 30
            'identity' => $identity,
478 30
            'cookieBased' => $cookieBased,
479 30
            'duration' => $duration,
480
        ]));
481 30
    }
482
483
    /**
484
     * This method is invoked when calling [[logout()]] to log out a user.
485
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
486
     * If you override this method, make sure you call the parent implementation
487
     * so that the event is triggered.
488
     * @param IdentityInterface $identity the user identity information
489
     * @return bool whether the user should continue to be logged out
490
     */
491
    protected function beforeLogout($identity)
492
    {
493
        $event = new UserEvent([
494
            'identity' => $identity,
495
        ]);
496
        $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
497
498
        return $event->isValid;
499
    }
500
501
    /**
502
     * This method is invoked right after a user is logged out via [[logout()]].
503
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
504
     * If you override this method, make sure you call the parent implementation
505
     * so that the event is triggered.
506
     * @param IdentityInterface $identity the user identity information
507
     */
508
    protected function afterLogout($identity)
509
    {
510
        $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
511
            'identity' => $identity,
512
        ]));
513
    }
514
515
    /**
516
     * Renews the identity cookie.
517
     * This method will set the expiration time of the identity cookie to be the current time
518
     * plus the originally specified cookie duration.
519
     */
520
    protected function renewIdentityCookie()
521
    {
522
        $name = $this->identityCookie['name'];
523
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
524
        if ($value !== null) {
525
            $data = json_decode($value, true);
526
            if (is_array($data) && isset($data[2])) {
527
                $cookie = Yii::createObject(array_merge($this->identityCookie, [
528
                    'class' => 'yii\web\Cookie',
529
                    'value' => $value,
530
                    'expire' => time() + (int) $data[2],
531
                ]));
532
                Yii::$app->getResponse()->getCookies()->add($cookie);
533
            }
534
        }
535
    }
536
537
    /**
538
     * Sends an identity cookie.
539
     * This method is used when [[enableAutoLogin]] is true.
540
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
541
     * information in the cookie.
542
     * @param IdentityInterface $identity
543
     * @param int $duration number of seconds that the user can remain in logged-in status.
544
     * @see loginByCookie()
545
     */
546 2
    protected function sendIdentityCookie($identity, $duration)
547
    {
548 2
        $cookie = Yii::createObject(array_merge($this->identityCookie, [
549 2
            'class' => 'yii\web\Cookie',
550 2
            'value' => json_encode([
551 2
                $identity->getId(),
552 2
                $identity->getAuthKey(),
553 2
                $duration,
554 2
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
555 2
            'expire' => time() + $duration,
556
        ]));
557 2
        Yii::$app->getResponse()->getCookies()->add($cookie);
558 2
    }
559
560
    /**
561
     * Determines if an identity cookie has a valid format and contains a valid auth key.
562
     * This method is used when [[enableAutoLogin]] is true.
563
     * This method attempts to authenticate a user using the information in the identity cookie.
564
     * @return array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
565
     * @see loginByCookie()
566
     * @since 2.0.9
567
     */
568 2
    protected function getIdentityAndDurationFromCookie()
569
    {
570 2
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
571 2
        if ($value === null) {
572
            return null;
573
        }
574 2
        $data = json_decode($value, true);
575 2
        if (is_array($data) && count($data) == 3) {
576 1
            list($id, $authKey, $duration) = $data;
577
            /* @var $class IdentityInterface */
578 1
            $class = $this->identityClass;
579 1
            $identity = $class::findIdentity($id);
580 1
            if ($identity !== null) {
581 1
                if (!$identity instanceof IdentityInterface) {
582
                    throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
583 1
                } elseif (!$identity->validateAuthKey($authKey)) {
584
                    Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
585
                } else {
586 1
                    return ['identity' => $identity, 'duration' => $duration];
587
                }
588
            }
589
        }
590 2
        $this->removeIdentityCookie();
591 2
        return null;
592
    }
593
594
    /**
595
     * Removes the identity cookie.
596
     * This method is used when [[enableAutoLogin]] is true.
597
     * @since 2.0.9
598
     */
599 2
    protected function removeIdentityCookie()
600
    {
601 2
        Yii::$app->getResponse()->getCookies()->remove(Yii::createObject(array_merge($this->identityCookie, [
602 2
            'class' => 'yii\web\Cookie',
603
        ])));
604 2
    }
605
606
    /**
607
     * Switches to a new identity for the current user.
608
     *
609
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
610
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
611
     *
612
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
613
     * when the current user needs to be associated with the corresponding identity information.
614
     *
615
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
616
     * If null, it means switching the current user to be a guest.
617
     * @param int $duration number of seconds that the user can remain in logged-in status.
618
     * This parameter is used only when `$identity` is not null.
619
     */
620 33
    public function switchIdentity($identity, $duration = 0)
621
    {
622 33
        $this->setIdentity($identity);
623
624 33
        if (!$this->enableSession) {
625
            return;
626
        }
627
628
        /* Ensure any existing identity cookies are removed. */
629 33
        if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
630 1
            $this->removeIdentityCookie();
631
        }
632
633 33
        $session = Yii::$app->getSession();
0 ignored issues
show
Bug introduced by
The method getSession 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...
634 33
        if (!YII_ENV_TEST) {
635
            $session->regenerateID(true);
636
        }
637 33
        $session->remove($this->idParam);
638 33
        $session->remove($this->authTimeoutParam);
639
640 33
        if ($identity) {
641 33
            $session->set($this->idParam, $identity->getId());
642 33
            if ($this->authTimeout !== null) {
643 1
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
644
            }
645 33
            if ($this->absoluteAuthTimeout !== null) {
646
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
647
            }
648 33
            if ($this->enableAutoLogin && $duration > 0) {
649 2
                $this->sendIdentityCookie($identity, $duration);
650
            }
651
        }
652
653
        // regenerate CSRF token
654 33
        Yii::$app->getRequest()->getCsrfToken(true);
655 33
    }
656
657
    /**
658
     * Updates the authentication status using the information from session and cookie.
659
     *
660
     * This method will try to determine the user identity using the [[idParam]] session variable.
661
     *
662
     * If [[authTimeout]] is set, this method will refresh the timer.
663
     *
664
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
665
     * if [[enableAutoLogin]] is true.
666
     */
667 23
    protected function renewAuthStatus()
668
    {
669 23
        $session = Yii::$app->getSession();
0 ignored issues
show
Bug introduced by
The method getSession 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...
670 23
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
671
672 23
        if ($id === null) {
673 22
            $identity = null;
674
        } else {
675
            /* @var $class IdentityInterface */
676 2
            $class = $this->identityClass;
677 2
            $identity = $class::findIdentity($id);
678
        }
679
680 22
        $this->setIdentity($identity);
681
682 22
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
683 1
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
684 1
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
685 1
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
686
                $this->logout(false);
687 1
            } elseif ($this->authTimeout !== null) {
688 1
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
689
            }
690
        }
691
692 22
        if ($this->enableAutoLogin) {
693 2
            if ($this->getIsGuest()) {
694 2
                $this->loginByCookie();
695 1
            } elseif ($this->autoRenewCookie) {
696
                $this->renewIdentityCookie();
697
            }
698
        }
699 22
    }
700
701
    /**
702
     * Checks if the user can perform the operation as specified by the given permission.
703
     *
704
     * Note that you must configure "authManager" application component in order to use this method.
705
     * Otherwise it will always return false.
706
     *
707
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
708
     * @param array $params name-value pairs that would be passed to the rules associated
709
     * with the roles and permissions assigned to the user.
710
     * @param bool $allowCaching whether to allow caching the result of access check.
711
     * When this parameter is true (default), if the access check of an operation was performed
712
     * before, its result will be directly returned when calling this method to check the same
713
     * operation. If this parameter is false, this method will always call
714
     * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
715
     * caching is effective only within the same request and only works when `$params = []`.
716
     * @return bool whether the user can perform the operation as specified by the given permission.
717
     */
718 20
    public function can($permissionName, $params = [], $allowCaching = true)
719
    {
720 20
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
721
            return $this->_access[$permissionName];
722
        }
723 20
        if (($accessChecker = $this->getAccessChecker()) === null) {
724
            return false;
725
        }
726 20
        $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
727 20
        if ($allowCaching && empty($params)) {
728 8
            $this->_access[$permissionName] = $access;
729
        }
730
731 20
        return $access;
732
    }
733
734
    /**
735
     * Checks if the `Accept` header contains a content type that allows redirection to the login page.
736
     * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
737
     * content types by modifying [[acceptableRedirectTypes]] property.
738
     * @return bool whether this request may be redirected to the login page.
739
     * @see acceptableRedirectTypes
740
     * @since 2.0.8
741
     */
742 2
    protected function checkRedirectAcceptable()
743
    {
744 2
        $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
745 2
        if (empty($acceptableTypes) || count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*') {
746 1
            return true;
747
        }
748
749 2
        foreach ($acceptableTypes as $type => $params) {
750 2
            if (in_array($type, $this->acceptableRedirectTypes, true)) {
751 2
                return true;
752
            }
753
        }
754
755 2
        return false;
756
    }
757
758
    /**
759
     * Returns auth manager associated with the user component.
760
     *
761
     * By default this is the `authManager` application component.
762
     * You may override this method to return a different auth manager instance if needed.
763
     * @return \yii\rbac\ManagerInterface
764
     * @since 2.0.6
765
     * @deprecated since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
766
     */
767
    protected function getAuthManager()
768
    {
769
        return Yii::$app->getAuthManager();
770
    }
771
772
    /**
773
     * Returns the access checker used for checking access.
774
     * @return CheckAccessInterface
775
     * @since 2.0.9
776
     */
777 20
    protected function getAccessChecker()
778
    {
779 20
        return $this->accessChecker !== null ? $this->accessChecker : $this->getAuthManager();
0 ignored issues
show
Deprecated Code introduced by
The method yii\web\User::getAuthManager() has been deprecated with message: since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
780
    }
781
}
782