PHP 클래스 yii\web\User
You may use [[isGuest]] to determine whether the current user is a guest or not.
If the user is a guest, the [[identity]] property would return null. Otherwise, it would
be an instance of
IdentityInterface.
You may call various methods to change the user authentication status:
-
User::login: sets the specified identity and remembers the authentication status in session and cookie.
-
User::logout: marks the user as a guest and clears the relevant information from session and cookie.
-
User::setIdentity: changes the user identity without touching session or cookie.
This is best used in stateless RESTful API implementation.
Note that User only maintains the user authentication status. It does NOT handle how to authenticate
a user. The logic of how to authenticate a user should be done in the class implementing
IdentityInterface.
You are also required to set [[identityClass]] with the name of this class.
User is configured as an application component in
Application by default.
You can access that instance via
Yii::$app->user.
You can modify its configuration by adding an array to your application config under
components
as it is shown in the following example:
~~~
'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
'loginUrl' => ['user/login'],
...
]
~~~
파일 보기
프로젝트 열기: yiisoft/yii2
1 사용 예제들
공개 프로퍼티들
프로퍼티 |
타입 |
설명 |
|
$absoluteAuthTimeout |
|
the number of seconds in which the user will be logged out automatically
regardless of activity.
Note that this will not work if [[enableAutoLogin]] is true. |
|
$absoluteAuthTimeoutParam |
|
the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
This is used when [[absoluteAuthTimeout]] is set. |
|
$acceptableRedirectTypes |
|
MIME types for which this component should redirect to the [[loginUrl]]. |
|
$accessChecker |
|
The access checker to use for checking access.
If not set the application auth manager will be used. |
|
$authTimeout |
|
the number of seconds in which the user will be logged out automatically if he
remains inactive. If this property is not set, the user will be logged out after
the current session expires (c.f. [[Session::timeout]]).
Note that this will not work if [[enableAutoLogin]] is true. |
|
$authTimeoutParam |
|
the session variable name used to store the value of expiration timestamp of the authenticated state.
This is used when [[authTimeout]] is set. |
|
$autoRenewCookie |
|
whether to automatically renew the identity cookie each time a page is requested.
This property is effective only when [[enableAutoLogin]] is true.
When this is false, the identity cookie will expire after the specified duration since the user
is initially logged in. When this is true, the identity cookie will expire after the specified duration
since the user visits the site the last time. |
|
$enableAutoLogin |
|
whether to enable cookie-based login. Defaults to false.
Note that this property will be ignored if [[enableSession]] is false. |
|
$enableSession |
|
whether to use session to persist authentication status across multiple requests.
You set this property to be false if your application is stateless, which is often the case
for RESTful APIs. |
|
$idParam |
|
the session variable name used to store the value of [[id]]. |
|
$identityClass |
|
the class name of the [[identity]] object. |
|
$identityCookie |
|
the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true. |
|
$loginUrl |
|
the URL for login when User::loginRequired is called.
If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
The first element of the array should be the route to the login action, and the rest of
the name-value pairs are GET parameters used to construct the login URL. For example,
php
['site/login', 'ref' => 1]
If this property is null, a 403 HTTP exception will be raised when User::loginRequired is called. |
|
$returnUrlParam |
|
the session variable name used to store the value of [[returnUrl]]. |
|
공개 메소드들
메소드 |
설명 |
|
can ( string $permissionName, array $params = [], boolean $allowCaching = true ) : boolean |
Checks if the user can perform the operation as specified by the given permission. |
|
getId ( ) : string | integer |
Returns a value that uniquely represents the user. |
|
getIdentity ( boolean $autoRenew = true ) : yii\web\IdentityInterface | null |
Returns the identity object associated with the currently logged-in user. |
|
getIsGuest ( ) : boolean |
Returns a value indicating whether the user is a guest (not authenticated). |
|
getReturnUrl ( string | array $defaultUrl = null ) : string |
Returns the URL that the browser should be redirected to after successful login. |
|
init ( ) |
Initializes the application component. |
|
login ( yii\web\IdentityInterface $identity, integer $duration ) : boolean |
Logs in a user. |
|
loginByAccessToken ( string $token, mixed $type = null ) : yii\web\IdentityInterface | null |
Logs in a user by the given access token. |
|
loginRequired ( boolean $checkAjax = true, boolean $checkAcceptHeader = true ) : Response |
Redirects the user browser to the login page. |
|
logout ( boolean $destroySession = true ) : boolean |
Logs out the current user. |
|
setIdentity ( yii\web\IdentityInterface | null $identity ) |
Sets the user identity object. |
|
setReturnUrl ( string | array $url ) |
Remembers the URL in the session so that it can be retrieved back later by User::getReturnUrl. |
|
switchIdentity ( yii\web\IdentityInterface | null $identity, integer $duration ) |
Switches to a new identity for the current user. |
|
보호된 메소드들
메소드 상세
The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
If you override this method, make sure you call the parent implementation
so that the event is triggered.
protected afterLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration ) |
$identity |
yii\web\IdentityInterface |
the user identity information |
$cookieBased |
boolean |
whether the login is cookie-based |
$duration |
integer |
number of seconds that the user can remain in logged-in status.
If 0, it means login till the user closes the browser or the session is manually destroyed. |
The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
If you override this method, make sure you call the parent implementation
so that the event is triggered.
protected afterLogout ( yii\web\IdentityInterface $identity ) |
$identity |
yii\web\IdentityInterface |
the user identity information |
The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
If you override this method, make sure you call the parent implementation
so that the event is triggered.
protected beforeLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration ) : boolean |
$identity |
yii\web\IdentityInterface |
the user identity information |
$cookieBased |
boolean |
whether the login is cookie-based |
$duration |
integer |
number of seconds that the user can remain in logged-in status.
If 0, it means login till the user closes the browser or the session is manually destroyed. |
리턴 |
boolean |
whether the user should continue to be logged in |
The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
If you override this method, make sure you call the parent implementation
so that the event is triggered.
protected beforeLogout ( yii\web\IdentityInterface $identity ) : boolean |
$identity |
yii\web\IdentityInterface |
the user identity information |
리턴 |
boolean |
whether the user should continue to be logged out |
Note that you must configure "authManager" application component in order to use this method.
Otherwise it will always return false.
public can ( string $permissionName, array $params = [], boolean $allowCaching = true ) : boolean |
$permissionName |
string |
the name of the permission (e.g. "edit post") that needs access check. |
$params |
array |
name-value pairs that would be passed to the rules associated
with the roles and permissions assigned to the user. |
$allowCaching |
boolean |
whether to allow caching the result of access check.
When this parameter is true (default), if the access check of an operation was performed
before, its result will be directly returned when calling this method to check the same
operation. If this parameter is false, this method will always call
[[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
caching is effective only within the same request and only works when `$params = []`. |
리턴 |
boolean |
whether the user can perform the operation as specified by the given permission. |
checkRedirectAcceptable()
보호된 메소드
The login page is assumed to serve text/html or application/xhtml+xml by default. You can change acceptable
content types by modifying [[acceptableRedirectTypes]] property.
getAccessChecker()
보호된 메소드
Returns the access checker used for checking access.
protected getAccessChecker ( ) : yii\rbac\CheckAccessInterface |
리턴 |
yii\rbac\CheckAccessInterface |
|
By default this is the authManager application component.
You may override this method to return a different auth manager instance if needed.
protected getAuthManager ( ) : yii\rbac\ManagerInterface |
리턴 |
yii\rbac\ManagerInterface |
|
Returns a value that uniquely represents the user.
When [[enableSession]] is true, this method may attempt to read the user's authentication data
stored in session and reconstruct the corresponding identity object, if it has not done so before.
public getIdentity ( boolean $autoRenew = true ) : yii\web\IdentityInterface | null |
$autoRenew |
boolean |
whether to automatically renew authentication status if it has not been done so before.
This is only useful when [[enableSession]] is true. |
리턴 |
yii\web\IdentityInterface | null |
the identity object associated with the currently logged-in user.
`null` is returned if the user is not logged in (not authenticated). |
getIdentityAndDurationFromCookie()
보호된 메소드
This method is used when [[enableAutoLogin]] is true.
This method attempts to authenticate a user using the information in the identity cookie.
Returns a value indicating whether the user is a guest (not authenticated).
This method reads the return URL from the session. It is usually used by the login action which
may call this method to redirect the browser to where it goes after successful authentication.
public getReturnUrl ( string | array $defaultUrl = null ) : string |
$defaultUrl |
string | array |
the default return URL in case it was not set previously.
If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
Please refer to [[setReturnUrl()]] on accepted format of the URL. |
리턴 |
string |
the URL that the user should be redirected to after login. |
Initializes the application component.
After logging in a user:
- the user's identity information is obtainable from the [[identity]] property
If [[enableSession]] is true:
- the identity information will be stored in session and be available in the next requests
- in case of $duration == 0: as long as the session remains active or till the user closes the browser
- in case of $duration > 0: as long as the session remains active or as long as the cookie
remains valid by it's $duration in seconds when [[enableAutoLogin]] is set true.
If [[enableSession]] is false:
- the $duration parameter will be ignored
public login ( yii\web\IdentityInterface $identity, integer $duration ) : boolean |
$identity |
yii\web\IdentityInterface |
the user identity (which should already be authenticated) |
$duration |
integer |
number of seconds that the user can remain in logged-in status, defaults to `0` |
리턴 |
boolean |
whether the user is logged in |
loginByAccessToken()
공개 메소드
This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
with the provided access token. If successful, it will call
User::login to log in the authenticated user.
If authentication fails or
User::login is unsuccessful, it will return null.
public loginByAccessToken ( string $token, mixed $type = null ) : yii\web\IdentityInterface | null |
$token |
string |
the access token |
$type |
mixed |
the type of the token. The value of this parameter depends on the implementation.
For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`. |
리턴 |
yii\web\IdentityInterface | null |
the identity associated with the given access token. Null is returned if
the access token is invalid or [[login()]] is unsuccessful. |
This method attempts to log in a user using the ID and authKey information
provided by the [[identityCookie|identity cookie]].
Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
the user browser may be redirected back to the current page after successful login.
Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
calling this method.
Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
public loginRequired ( boolean $checkAjax = true, boolean $checkAcceptHeader = true ) : Response |
$checkAjax |
boolean |
whether to check if the request is an AJAX request. When this is true and the request
is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL. |
$checkAcceptHeader |
boolean |
whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8. |
리턴 |
Response |
the redirection response if [[loginUrl]] is set |
This will remove authentication-related session data.
If $destroySession is true, all session data will be removed.
public logout ( boolean $destroySession = true ) : boolean |
$destroySession |
boolean |
whether to destroy the whole session. Defaults to true.
This parameter is ignored if [[enableSession]] is false. |
리턴 |
boolean |
whether the user is logged out |
removeIdentityCookie()
보호된 메소드
This method is used when [[enableAutoLogin]] is true.
renewAuthStatus()
보호된 메소드
This method will try to determine the user identity using the [[idParam]] session variable.
If [[authTimeout]] is set, this method will refresh the timer.
If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
if [[enableAutoLogin]] is true.
renewIdentityCookie()
보호된 메소드
This method will set the expiration time of the identity cookie to be the current time
plus the originally specified cookie duration.
sendIdentityCookie()
보호된 메소드
This method is used when [[enableAutoLogin]] is true.
It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
information in the cookie.
protected sendIdentityCookie ( yii\web\IdentityInterface $identity, integer $duration ) |
$identity |
yii\web\IdentityInterface |
|
$duration |
integer |
number of seconds that the user can remain in logged-in status. |
Note that this method does not deal with session or cookie. You should usually use
User::switchIdentity
to change the identity of the current user.
public setIdentity ( yii\web\IdentityInterface | null $identity ) |
$identity |
yii\web\IdentityInterface | null |
the identity object associated with the currently logged user.
If null, it means the current user will be a guest without any associated identity. |
Remembers the URL in the session so that it can be retrieved back later by
User::getReturnUrl.
public setReturnUrl ( string | array $url ) |
$url |
string | array |
the URL that the user should be redirected to after login.
If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
The first element of the array should be the route, and the rest of
the name-value pairs are GET parameters used to construct the URL. For example,
```php
['admin/index', 'ref' => 1]
``` |
When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
according to the value of
$duration. Please refer to
User::login for more details.
This method is mainly called by
User::login,
User::logout and
User::loginByCookie
when the current user needs to be associated with the corresponding identity information.
public switchIdentity ( yii\web\IdentityInterface | null $identity, integer $duration ) |
$identity |
yii\web\IdentityInterface | null |
the identity information to be associated with the current user.
If null, it means switching the current user to be a guest. |
$duration |
integer |
number of seconds that the user can remain in logged-in status.
This parameter is used only when `$identity` is not null. |
프로퍼티 상세
$absoluteAuthTimeout 공개적으로 프로퍼티
the number of seconds in which the user will be logged out automatically
regardless of activity.
Note that this will not work if [[enableAutoLogin]] is true.
public $absoluteAuthTimeout |
$absoluteAuthTimeoutParam 공개적으로 프로퍼티
the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
This is used when [[absoluteAuthTimeout]] is set.
public $absoluteAuthTimeoutParam |
$acceptableRedirectTypes 공개적으로 프로퍼티
MIME types for which this component should redirect to the [[loginUrl]].
public $acceptableRedirectTypes |
$accessChecker 공개적으로 프로퍼티
The access checker to use for checking access.
If not set the application auth manager will be used.
the number of seconds in which the user will be logged out automatically if he
remains inactive. If this property is not set, the user will be logged out after
the current session expires (c.f. [[Session::timeout]]).
Note that this will not work if [[enableAutoLogin]] is true.
$authTimeoutParam 공개적으로 프로퍼티
the session variable name used to store the value of expiration timestamp of the authenticated state.
This is used when [[authTimeout]] is set.
$autoRenewCookie 공개적으로 프로퍼티
whether to automatically renew the identity cookie each time a page is requested.
This property is effective only when [[enableAutoLogin]] is true.
When this is false, the identity cookie will expire after the specified duration since the user
is initially logged in. When this is true, the identity cookie will expire after the specified duration
since the user visits the site the last time.
$enableAutoLogin 공개적으로 프로퍼티
whether to enable cookie-based login. Defaults to false.
Note that this property will be ignored if [[enableSession]] is false.
$enableSession 공개적으로 프로퍼티
whether to use session to persist authentication status across multiple requests.
You set this property to be false if your application is stateless, which is often the case
for RESTful APIs.
the session variable name used to store the value of [[id]].
$identityClass 공개적으로 프로퍼티
the class name of the [[identity]] object.
$identityCookie 공개적으로 프로퍼티
the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
the URL for login when
User::loginRequired is called.
If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
The first element of the array should be the route to the login action, and the rest of
the name-value pairs are GET parameters used to construct the login URL. For example,
php
['site/login', 'ref' => 1]
If this property is
null, a 403 HTTP exception will be raised when
User::loginRequired is called.
$returnUrlParam 공개적으로 프로퍼티
the session variable name used to store the value of [[returnUrl]].