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