Completed
Push — 3.0 ( e28bf1...6f19d3 )
by Alexander
113:15 queued 105:35
created

User::setIdentity()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
ccs 7
cts 8
cp 0.875
cc 3
nc 3
nop 1
crap 3.0175
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\http\Cookie;
15
use yii\rbac\CheckAccessInterface;
16
17
/**
18
 * User is the class for the `user` application component that manages the user authentication status.
19
 *
20
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
21
 * If the user is a guest, the [[identity]] property would return `null`. Otherwise, it would
22
 * be an instance of [[IdentityInterface]].
23
 *
24
 * You may call various methods to change the user authentication status:
25
 *
26
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
27
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
28
 * - [[setIdentity()]]: changes the user identity without touching session or cookie
29
 *   (this is best used in stateless RESTful API implementation).
30
 *
31
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
32
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
33
 * You are also required to set [[identityClass]] with the name of this class.
34
 *
35
 * User is configured as an application component in [[\yii\web\Application]] by default.
36
 * You can access that instance via `Yii::$app->user`.
37
 *
38
 * You can modify its configuration by adding an array to your application config under `components`
39
 * as it is shown in the following example:
40
 *
41
 * ```php
42
 * 'user' => [
43
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
44
 *     'enableAutoLogin' => true,
45
 *     // 'loginUrl' => ['user/login'],
46
 *     // ...
47
 * ]
48
 * ```
49
 *
50
 * @property string|int $id The unique identifier for the user. If `null`, it means the user is a guest. This
51
 * property is read-only.
52
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
53
 * user. `null` is returned if the user is not logged in (not authenticated).
54
 * @property bool $isGuest Whether the current user is a guest. This property is read-only.
55
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
56
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
57
 *
58
 * @author Qiang Xue <[email protected]>
59
 * @since 2.0
60
 */
61
class User extends Component
62
{
63
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
64
    const EVENT_AFTER_LOGIN = 'afterLogin';
65
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
66
    const EVENT_AFTER_LOGOUT = 'afterLogout';
67
68
    /**
69
     * @var string the class name of the [[identity]] object.
70
     */
71
    public $identityClass;
72
    /**
73
     * @var bool whether to enable cookie-based login. Defaults to `false`.
74
     * Note that this property will be ignored if [[enableSession]] is `false`.
75
     */
76
    public $enableAutoLogin = false;
77
    /**
78
     * @var bool whether to use session to persist authentication status across multiple requests.
79
     * You set this property to be `false` if your application is stateless, which is often the case
80
     * for RESTful APIs.
81
     */
82
    public $enableSession = true;
83
    /**
84
     * @var string|array the URL for login when [[loginRequired()]] is called.
85
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
86
     * The first element of the array should be the route to the login action, and the rest of
87
     * the name-value pairs are GET parameters used to construct the login URL. For example,
88
     *
89
     * ```php
90
     * ['site/login', 'ref' => 1]
91
     * ```
92
     *
93
     * If this property is `null`, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
94
     */
95
    public $loginUrl = ['site/login'];
96
    /**
97
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is `true`.
98
     * @see Cookie
99
     */
100
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
101
    /**
102
     * @var int the number of seconds in which the user will be logged out automatically if he
103
     * remains inactive. If this property is not set, the user will be logged out after
104
     * the current session expires (c.f. [[Session::timeout]]).
105
     * Note that this will not work if [[enableAutoLogin]] is `true`.
106
     */
107
    public $authTimeout;
108
    /**
109
     * @var CheckAccessInterface The access checker to use for checking access.
110
     * If not set the application auth manager will be used.
111
     * @since 2.0.9
112
     */
113
    public $accessChecker;
114
    /**
115
     * @var int the number of seconds in which the user will be logged out automatically
116
     * regardless of activity.
117
     * Note that this will not work if [[enableAutoLogin]] is `true`.
118
     */
119
    public $absoluteAuthTimeout;
120
    /**
121
     * @var bool whether to automatically renew the identity cookie each time a page is requested.
122
     * This property is effective only when [[enableAutoLogin]] is `true`.
123
     * When this is `false`, the identity cookie will expire after the specified duration since the user
124
     * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration
125
     * since the user visits the site the last time.
126
     * @see enableAutoLogin
127
     */
128
    public $autoRenewCookie = true;
129
    /**
130
     * @var string the session variable name used to store the value of [[id]].
131
     */
132
    public $idParam = '__id';
133
    /**
134
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
135
     * This is used when [[authTimeout]] is set.
136
     */
137
    public $authTimeoutParam = '__expire';
138
    /**
139
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
140
     * This is used when [[absoluteAuthTimeout]] is set.
141
     */
142
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
143
    /**
144
     * @var string the session variable name used to store the value of [[returnUrl]].
145
     */
146
    public $returnUrlParam = '__returnUrl';
147
    /**
148
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
149
     * @since 2.0.8
150
     */
151
    public $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
152
153
    private $_access = [];
154
155
156
    /**
157
     * Initializes the application component.
158
     */
159 60
    public function init()
160
    {
161 60
        parent::init();
162
163 60
        if ($this->identityClass === null) {
164
            throw new InvalidConfigException('User::identityClass must be set.');
165
        }
166 60
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
167
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
168
        }
169 60
        if (!empty($this->accessChecker) && is_string($this->accessChecker)) {
170 1
            $this->accessChecker = Yii::createObject($this->accessChecker);
171
        }
172 60
    }
173
174
    private $_identity = false;
175
176
    /**
177
     * Returns the identity object associated with the currently logged-in user.
178
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
179
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
180
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
181
     * This is only useful when [[enableSession]] is true.
182
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
183
     * `null` is returned if the user is not logged in (not authenticated).
184
     * @see login()
185
     * @see logout()
186
     */
187 51
    public function getIdentity($autoRenew = true)
188
    {
189 51
        if ($this->_identity === false) {
190 17
            if ($this->enableSession && $autoRenew) {
191
                try {
192 16
                    $this->_identity = null;
193 16
                    $this->renewAuthStatus();
194 1
                } catch (\Exception $e) {
195 1
                    $this->_identity = false;
196 1
                    throw $e;
197
                } catch (\Throwable $e) {
198
                    $this->_identity = false;
199 15
                    throw $e;
200
                }
201
            } else {
202 1
                return null;
203
            }
204
        }
205
206 49
        return $this->_identity;
207
    }
208
209
    /**
210
     * Sets the user identity object.
211
     *
212
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
213
     * to change the identity of the current user.
214
     *
215
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
216
     * If null, it means the current user will be a guest without any associated identity.
217
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
218
     */
219 49
    public function setIdentity($identity)
220
    {
221 49
        if ($identity instanceof IdentityInterface) {
222 33
            $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...
223 33
            $this->_access = [];
224 22
        } elseif ($identity === null) {
225 22
            $this->_identity = null;
226
        } else {
227
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
228
        }
229 49
    }
230
231
    /**
232
     * Logs in a user.
233
     *
234
     * After logging in a user:
235
     * - the user's identity information is obtainable from the [[identity]] property
236
     *
237
     * If [[enableSession]] is `true`:
238
     * - the identity information will be stored in session and be available in the next requests
239
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
240
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
241
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
242
     *
243
     * If [[enableSession]] is `false`:
244
     * - the `$duration` parameter will be ignored
245
     *
246
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
247
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
248
     * @return bool whether the user is logged in
249
     */
250 15
    public function login(IdentityInterface $identity, $duration = 0)
251
    {
252 15
        if ($this->beforeLogin($identity, false, $duration)) {
253 15
            $this->switchIdentity($identity, $duration);
254 15
            $id = $identity->getId();
255 15
            $ip = Yii::$app->getRequest()->getUserIP();
256 15
            if ($this->enableSession) {
257 15
                $log = "User '$id' logged in from $ip with duration $duration.";
258
            } else {
259
                $log = "User '$id' logged in from $ip. Session not enabled.";
260
            }
261
262 15
            $this->regenerateCsrfToken();
263
264 15
            Yii::info($log, __METHOD__);
265 15
            $this->afterLogin($identity, false, $duration);
266
        }
267
268 15
        return !$this->getIsGuest();
269
    }
270
271
    /**
272
     * Regenerates CSRF token
273
     *
274
     * @since 2.0.14.2
275
     */
276 15
    protected function regenerateCsrfToken()
277
    {
278 15
        $request = Yii::$app->getRequest();
279 15
        if ($request->enableCsrfCookie || $this->enableSession) {
280 15
            $request->getCsrfToken(true);
281
        }
282 15
    }
283
284
    /**
285
     * Logs in a user by the given access token.
286
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
287
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
288
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
289
     * @param string $token the access token
290
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
291
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
292
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
293
     * the access token is invalid or [[login()]] is unsuccessful.
294
     */
295 19
    public function loginByAccessToken($token, $type = null)
296
    {
297
        /* @var $class IdentityInterface */
298 19
        $class = $this->identityClass;
299 19
        $identity = $class::findIdentityByAccessToken($token, $type);
300 19
        if ($identity && $this->login($identity)) {
301 12
            return $identity;
302
        }
303
304 7
        return null;
305
    }
306
307
    /**
308
     * Logs in a user by cookie.
309
     *
310
     * This method attempts to log in a user using the ID and authKey information
311
     * provided by the [[identityCookie|identity cookie]].
312
     */
313 2
    protected function loginByCookie()
314
    {
315 2
        $data = $this->getIdentityAndDurationFromCookie();
316 2
        if (isset($data['identity'], $data['duration'])) {
317 1
            $identity = $data['identity'];
318 1
            $duration = $data['duration'];
319 1
            if ($this->beforeLogin($identity, true, $duration)) {
0 ignored issues
show
Documentation introduced by
$duration is of type object<yii\web\IdentityInterface>, but the function expects a integer.

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...
320 1
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
321 1
                $id = $identity->getId();
322 1
                $ip = Yii::$app->getRequest()->getUserIP();
323 1
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
324 1
                $this->afterLogin($identity, true, $duration);
0 ignored issues
show
Documentation introduced by
$duration is of type object<yii\web\IdentityInterface>, but the function expects a integer.

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...
325
            }
326
        }
327 2
    }
328
329
    /**
330
     * Logs out the current user.
331
     * This will remove authentication-related session data.
332
     * If `$destroySession` is true, all session data will be removed.
333
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
334
     * This parameter is ignored if [[enableSession]] is false.
335
     * @return bool whether the user is logged out
336
     */
337
    public function logout($destroySession = true)
338
    {
339
        $identity = $this->getIdentity();
340
        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...
341
            $this->switchIdentity(null);
342
            $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...
343
            $ip = Yii::$app->getRequest()->getUserIP();
344
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
345
            if ($destroySession && $this->enableSession) {
346
                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...
347
            }
348
            $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...
349
        }
350
351
        return $this->getIsGuest();
352
    }
353
354
    /**
355
     * Returns a value indicating whether the user is a guest (not authenticated).
356
     * @return bool whether the current user is a guest.
357
     * @see getIdentity()
358
     */
359 16
    public function getIsGuest()
360
    {
361 16
        return $this->getIdentity() === null;
362
    }
363
364
    /**
365
     * Returns a value that uniquely represents the user.
366
     * @return string|int the unique identifier for the user. If `null`, it means the user is a guest.
367
     * @see getIdentity()
368
     */
369 46
    public function getId()
370
    {
371 46
        $identity = $this->getIdentity();
372
373 46
        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...
374
    }
375
376
    /**
377
     * Returns the URL that the browser should be redirected to after successful login.
378
     *
379
     * This method reads the return URL from the session. It is usually used by the login action which
380
     * may call this method to redirect the browser to where it goes after successful authentication.
381
     *
382
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
383
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
384
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
385
     * @return string the URL that the user should be redirected to after login.
386
     * @see loginRequired()
387
     */
388 2
    public function getReturnUrl($defaultUrl = null)
389
    {
390 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...
391 2
        if (is_array($url)) {
392
            if (isset($url[0])) {
393
                return Yii::$app->getUrlManager()->createUrl($url);
394
            }
395
396
            $url = null;
397
        }
398
399 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...
400
    }
401
402
    /**
403
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
404
     * @param string|array $url the URL that the user should be redirected to after login.
405
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
406
     * The first element of the array should be the route, and the rest of
407
     * the name-value pairs are GET parameters used to construct the URL. For example,
408
     *
409
     * ```php
410
     * ['admin/index', 'ref' => 1]
411
     * ```
412
     */
413 2
    public function setReturnUrl($url)
414
    {
415 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...
416 2
    }
417
418
    /**
419
     * Redirects the user browser to the login page.
420
     *
421
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
422
     * the user browser may be redirected back to the current page after successful login.
423
     *
424
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
425
     * calling this method.
426
     *
427
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
428
     *
429
     * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
430
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
431
     * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
432
     * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
433
     * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
434
     * @return Response the redirection response if [[loginUrl]] is set
435
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
436
     * not applicable.
437
     */
438 2
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
439
    {
440 2
        $request = Yii::$app->getRequest();
441 2
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
442 2
        if ($this->enableSession
443 2
            && $request->getIsGet()
444 2
            && (!$checkAjax || !$request->getIsAjax())
445 2
            && $canRedirect
446
        ) {
447 1
            $this->setReturnUrl($request->getUrl());
448
        }
449 2
        if ($this->loginUrl !== null && $canRedirect) {
450 1
            $loginUrl = (array) $this->loginUrl;
451 1
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
452 1
                return Yii::$app->getResponse()->redirect($this->loginUrl);
453
            }
454
        }
455 2
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
456
    }
457
458
    /**
459
     * This method is called before logging in a user.
460
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
461
     * If you override this method, make sure you call the parent implementation
462
     * so that the event is triggered.
463
     * @param IdentityInterface $identity the user identity information
464
     * @param bool $cookieBased whether the login is cookie-based
465
     * @param int $duration number of seconds that the user can remain in logged-in status.
466
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
467
     * @return bool whether the user should continue to be logged in
468
     */
469 15
    protected function beforeLogin($identity, $cookieBased, $duration)
470
    {
471 15
        $event = new UserEvent([
472 15
            'name' => self::EVENT_BEFORE_LOGIN,
473 15
            'identity' => $identity,
474 15
            'cookieBased' => $cookieBased,
475 15
            'duration' => $duration,
476
        ]);
477 15
        $this->trigger($event);
478
479 15
        return $event->isValid;
480
    }
481
482
    /**
483
     * This method is called after the user is successfully logged in.
484
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
485
     * If you override this method, make sure you call the parent implementation
486
     * so that the event is triggered.
487
     * @param IdentityInterface $identity the user identity information
488
     * @param bool $cookieBased whether the login is cookie-based
489
     * @param int $duration number of seconds that the user can remain in logged-in status.
490
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
491
     */
492 15
    protected function afterLogin($identity, $cookieBased, $duration)
493
    {
494 15
        $this->trigger(new UserEvent([
495 15
            'name' => self::EVENT_AFTER_LOGIN,
496 15
            'identity' => $identity,
497 15
            'cookieBased' => $cookieBased,
498 15
            'duration' => $duration,
499
        ]));
500 15
    }
501
502
    /**
503
     * This method is invoked when calling [[logout()]] to log out a user.
504
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
505
     * If you override this method, make sure you call the parent implementation
506
     * so that the event is triggered.
507
     * @param IdentityInterface $identity the user identity information
508
     * @return bool whether the user should continue to be logged out
509
     */
510
    protected function beforeLogout($identity)
511
    {
512
        $event = new UserEvent([
513
            'name' => self::EVENT_BEFORE_LOGOUT,
514
            'identity' => $identity,
515
        ]);
516
        $this->trigger($event);
517
518
        return $event->isValid;
519
    }
520
521
    /**
522
     * This method is invoked right after a user is logged out via [[logout()]].
523
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
524
     * If you override this method, make sure you call the parent implementation
525
     * so that the event is triggered.
526
     * @param IdentityInterface $identity the user identity information
527
     */
528
    protected function afterLogout($identity)
529
    {
530
        $this->trigger(new UserEvent([
531
            'name' => self::EVENT_AFTER_LOGOUT,
532
            'identity' => $identity,
533
        ]));
534
    }
535
536
    /**
537
     * Renews the identity cookie.
538
     * This method will set the expiration time of the identity cookie to be the current time
539
     * plus the originally specified cookie duration.
540
     */
541
    protected function renewIdentityCookie()
542
    {
543
        $name = $this->identityCookie['name'];
544
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
545
        if ($value !== null) {
546
            $data = json_decode($value, true);
547
            if (is_array($data) && isset($data[2])) {
548
                $cookie = Yii::createObject(array_merge($this->identityCookie, [
549
                    '__class' => \yii\http\Cookie::class,
550
                    'value' => $value,
551
                    'expire' => time() + (int) $data[2],
552
                ]));
553
                Yii::$app->getResponse()->getCookies()->add($cookie);
554
            }
555
        }
556
    }
557
558
    /**
559
     * Sends an identity cookie.
560
     * This method is used when [[enableAutoLogin]] is true.
561
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
562
     * information in the cookie.
563
     * @param IdentityInterface $identity
564
     * @param int $duration number of seconds that the user can remain in logged-in status.
565
     * @see loginByCookie()
566
     */
567 2
    protected function sendIdentityCookie($identity, $duration)
568
    {
569 2
        $cookie = Yii::createObject(array_merge($this->identityCookie, [
570 2
            '__class' => \yii\http\Cookie::class,
571 2
            'value' => json_encode([
572 2
                $identity->getId(),
573 2
                $identity->getAuthKey(),
574 2
                $duration,
575 2
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
576 2
            'expire' => time() + $duration,
577
        ]));
578 2
        Yii::$app->getResponse()->getCookies()->add($cookie);
579 2
    }
580
581
    /**
582
     * Determines if an identity cookie has a valid format and contains a valid auth key.
583
     * This method is used when [[enableAutoLogin]] is true.
584
     * This method attempts to authenticate a user using the information in the identity cookie.
585
     * @return array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
586
     * @see loginByCookie()
587
     * @since 2.0.9
588
     */
589 2
    protected function getIdentityAndDurationFromCookie()
590
    {
591 2
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
592 2
        if ($value === null) {
593
            return null;
594
        }
595 2
        $data = json_decode($value, true);
596 2
        if (is_array($data) && count($data) == 3) {
597 1
            [$id, $authKey, $duration] = $data;
0 ignored issues
show
Bug introduced by
The variable $id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $authKey does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $duration does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
598
            /* @var $class IdentityInterface */
599 1
            $class = $this->identityClass;
600 1
            $identity = $class::findIdentity($id);
601 1
            if ($identity !== null) {
602 1
                if (!$identity instanceof IdentityInterface) {
603
                    throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
604 1
                } elseif (!$identity->validateAuthKey($authKey)) {
605
                    Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
606
                } else {
607 1
                    return ['identity' => $identity, 'duration' => $duration];
608
                }
609
            }
610
        }
611 2
        $this->removeIdentityCookie();
612 2
        return null;
613
    }
614
615
    /**
616
     * Removes the identity cookie.
617
     * This method is used when [[enableAutoLogin]] is true.
618
     * @since 2.0.9
619
     */
620 2
    protected function removeIdentityCookie()
621
    {
622 2
        Yii::$app->getResponse()->getCookies()->remove(Yii::createObject(array_merge($this->identityCookie, [
623 2
            '__class' => \yii\http\Cookie::class,
624
        ])));
625 2
    }
626
627
    /**
628
     * Switches to a new identity for the current user.
629
     *
630
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
631
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
632
     *
633
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
634
     * when the current user needs to be associated with the corresponding identity information.
635
     *
636
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
637
     * If null, it means switching the current user to be a guest.
638
     * @param int $duration number of seconds that the user can remain in logged-in status.
639
     * This parameter is used only when `$identity` is not null.
640
     */
641 18
    public function switchIdentity($identity, $duration = 0)
642
    {
643 18
        $this->setIdentity($identity);
644
645 18
        if (!$this->enableSession) {
646
            return;
647
        }
648
649
        /* Ensure any existing identity cookies are removed. */
650 18
        if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
651 1
            $this->removeIdentityCookie();
652
        }
653
654 18
        $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...
655 18
        if (!YII_ENV_TEST) {
656
            $session->regenerateID(true);
657
        }
658 18
        $session->remove($this->idParam);
659 18
        $session->remove($this->authTimeoutParam);
660
661 18
        if ($identity) {
662 18
            $session->set($this->idParam, $identity->getId());
663 18
            if ($this->authTimeout !== null) {
664 1
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
665
            }
666 18
            if ($this->absoluteAuthTimeout !== null) {
667
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
668
            }
669 18
            if ($this->enableAutoLogin && $duration > 0) {
670 2
                $this->sendIdentityCookie($identity, $duration);
671
            }
672
        }
673 18
    }
674
675
    /**
676
     * Updates the authentication status using the information from session and cookie.
677
     *
678
     * This method will try to determine the user identity using the [[idParam]] session variable.
679
     *
680
     * If [[authTimeout]] is set, this method will refresh the timer.
681
     *
682
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
683
     * if [[enableAutoLogin]] is true.
684
     */
685 16
    protected function renewAuthStatus()
686
    {
687 16
        $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...
688 16
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
689
690 16
        if ($id === null) {
691 15
            $identity = null;
692
        } else {
693
            /* @var $class IdentityInterface */
694 2
            $class = $this->identityClass;
695 2
            $identity = $class::findIdentity($id);
696
        }
697
698 15
        $this->setIdentity($identity);
699
700 15
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
701 1
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
702 1
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
703 1
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
704
                $this->logout(false);
705 1
            } elseif ($this->authTimeout !== null) {
706 1
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
707
            }
708
        }
709
710 15
        if ($this->enableAutoLogin) {
711 2
            if ($this->getIsGuest()) {
712 2
                $this->loginByCookie();
713 1
            } elseif ($this->autoRenewCookie) {
714
                $this->renewIdentityCookie();
715
            }
716
        }
717 15
    }
718
719
    /**
720
     * Checks if the user can perform the operation as specified by the given permission.
721
     *
722
     * Note that you must configure "authManager" application component in order to use this method.
723
     * Otherwise it will always return false.
724
     *
725
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
726
     * @param array $params name-value pairs that would be passed to the rules associated
727
     * with the roles and permissions assigned to the user.
728
     * @param bool $allowCaching whether to allow caching the result of access check.
729
     * When this parameter is true (default), if the access check of an operation was performed
730
     * before, its result will be directly returned when calling this method to check the same
731
     * operation. If this parameter is false, this method will always call
732
     * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
733
     * caching is effective only within the same request and only works when `$params = []`.
734
     * @return bool whether the user can perform the operation as specified by the given permission.
735
     */
736 20
    public function can($permissionName, $params = [], $allowCaching = true)
737
    {
738 20
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
739
            return $this->_access[$permissionName];
740
        }
741 20
        if (($accessChecker = $this->getAccessChecker()) === null) {
742
            return false;
743
        }
744 20
        $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
745 20
        if ($allowCaching && empty($params)) {
746 8
            $this->_access[$permissionName] = $access;
747
        }
748
749 20
        return $access;
750
    }
751
752
    /**
753
     * Checks if the `Accept` header contains a content type that allows redirection to the login page.
754
     * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
755
     * content types by modifying [[acceptableRedirectTypes]] property.
756
     * @return bool whether this request may be redirected to the login page.
757
     * @see acceptableRedirectTypes
758
     * @since 2.0.8
759
     */
760 2
    protected function checkRedirectAcceptable()
761
    {
762 2
        $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
763 2
        if (empty($acceptableTypes) || count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*') {
764 1
            return true;
765
        }
766
767 2
        foreach ($acceptableTypes as $type => $params) {
768 2
            if (in_array($type, $this->acceptableRedirectTypes, true)) {
769 2
                return true;
770
            }
771
        }
772
773 2
        return false;
774
    }
775
776
    /**
777
     * Returns the access checker used for checking access.
778
     *
779
     * By default this is the `authManager` application component.
780
     *
781
     * @return CheckAccessInterface
782
     * @since 2.0.9
783
     */
784 20
    protected function getAccessChecker()
785
    {
786 20
        return $this->accessChecker !== null ? $this->accessChecker : Yii::$app->getAuthManager();
787
    }
788
}
789