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