{"id":14966431,"url":"https://github.com/yiisoft/user","last_synced_at":"2025-04-07T06:07:29.253Z","repository":{"id":37097548,"uuid":"308556866","full_name":"yiisoft/user","owner":"yiisoft","description":"Convenient user identity management and access checking.","archived":false,"fork":false,"pushed_at":"2024-10-24T08:16:01.000Z","size":201,"stargazers_count":18,"open_issues_count":5,"forks_count":8,"subscribers_count":16,"default_branch":"master","last_synced_at":"2024-10-29T14:35:41.023Z","etag":null,"topics":["hacktoberfest","identity","login","logout","remember-me","user","yii3"],"latest_commit_sha":null,"homepage":"https://www.yiiframework.com/","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yiisoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"open_collective":"yiisoft","github":["yiisoft"]}},"created_at":"2020-10-30T07:33:30.000Z","updated_at":"2024-10-24T08:16:04.000Z","dependencies_parsed_at":"2023-12-13T03:33:17.788Z","dependency_job_id":"8c349f24-19eb-4fa9-814f-c770bca67995","html_url":"https://github.com/yiisoft/user","commit_stats":{"total_commits":107,"total_committers":14,"mean_commits":7.642857142857143,"dds":0.7757009345794392,"last_synced_commit":"8995f027c9ab1a80e4f9f8111887bd522b4b1432"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":"yiisoft/package-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fuser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fuser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fuser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Fuser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yiisoft","download_url":"https://codeload.github.com/yiisoft/user/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247415792,"owners_count":20935383,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","identity","login","logout","remember-me","user","yii3"],"created_at":"2024-09-24T13:36:22.644Z","updated_at":"2025-04-07T06:07:29.225Z","avatar_url":"https://github.com/yiisoft.png","language":"PHP","funding_links":["https://opencollective.com/yiisoft","https://github.com/sponsors/yiisoft"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yiisoft\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://yiisoft.github.io/docs/images/yii_logo.svg\" height=\"100px\" alt=\"Yii\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eYii User\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\n[![Latest Stable Version](https://poser.pugx.org/yiisoft/user/v)](https://packagist.org/packages/yiisoft/user)\n[![Total Downloads](https://poser.pugx.org/yiisoft/user/downloads)](https://packagist.org/packages/yiisoft/user)\n[![Build status](https://github.com/yiisoft/user/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/user/actions/workflows/build.yml)\n[![Code Coverage](https://codecov.io/gh/yiisoft/user/graph/badge.svg?token=ILNFVY8C26)](https://codecov.io/gh/yiisoft/user)\n[![Mutation testing badge](https://img.shields.io/endpoint?style=flat\u0026url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fyiisoft%2Fuser%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/user/master)\n[![static analysis](https://github.com/yiisoft/user/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/user/actions?query=workflow%3A%22static+analysis%22)\n[![type-coverage](https://shepherd.dev/github/yiisoft/user/coverage.svg)](https://shepherd.dev/github/yiisoft/user)\n\nThe package handles user-related functionality:\n\n- Login and logout.\n- Getting currently logged in identity.\n- Changing current identity.\n- Access checking for current user.\n- Auto login based on identity from request attribute.\n- Auto login or \"remember me\" based on request cookie.\n\n## Requirements\n\n- PHP 8.1 or higher.\n\n## Installation\n\nThe package could be installed with [Composer](https://getcomposer.org):\n\n```shell\ncomposer require yiisoft/user\n```\n\n## General usage\n\nThis package is an addition to [yiisoft/auth](https://github.com/yiisoft/auth)\nand provides additional functionality for interacting with user identity.\n\n### Working with identity\n\nThe `CurrentUser` class is responsible for login and logout, as well as for providing data about the current user identity.\n\n```php\n/** \n * @var \\Psr\\EventDispatcher\\EventDispatcherInterface $eventDispatcher\n * @var \\Yiisoft\\Auth\\IdentityRepositoryInterface $identityRepository\n */\n\n$currentUser = new \\Yiisoft\\User\\CurrentUser($identityRepository, $eventDispatcher);\n```\n\nIf the user has not been logged in, then the current user is a guest:\n\n```php\n$currentUser-\u003egetIdentity(); // \\Yiisoft\\User\\Guest\\GuestIdentity instance\n$currentUser-\u003egetId(); // null\n$currentUser-\u003eisGuest(); // bool\n```\n\nIf you need to use a custom identity class to represent guest user, you should pass an instance\nof `GuestIdentityFactoryInterface` as a third optional parameter when creating `CurrentUser`:\n\n```php\n/** \n * @var \\Psr\\EventDispatcher\\EventDispatcherInterface $eventDispatcher\n * @var \\Yiisoft\\Auth\\IdentityRepositoryInterface $identityRepository\n * @var \\Yiisoft\\User\\Guest\\GuestIdentityFactoryInterface $guestIdentityFactory\n */\n\n$currentUser = new \\Yiisoft\\User\\CurrentUser($identityRepository, $eventDispatcher, $guestIdentityFactory);\n```\n\nAlso, you can override an identity instance in runtime:\n\n```php\n/** \n * @var \\Yiisoft\\Auth\\IdentityInterface $identity\n */\n\n$currentUser-\u003egetIdentity(); // Original identity instance\n$currentUser-\u003eoverrideIdentity($identity);\n$currentUser-\u003egetIdentity(); // Override identity instance\n$currentUser-\u003eclearIdentityOverride();\n$currentUser-\u003egetIdentity(); // Original identity instance\n```\n\nIt can be useful to allow admin or developer to validate another user's problems.\n\n#### Login and logout\n\nThere are two methods for login and logout:\n\n```php\n/**\n * @var \\Yiisoft\\Auth\\IdentityInterface $identity\n */\n\n$currentUser-\u003egetIdentity(); // GuestIdentityInterface instance\n\nif ($currentUser-\u003elogin($identity)) {\n    $currentUser-\u003egetIdentity(); // $identity\n    // Some actions\n}\n\nif ($currentUser-\u003elogout()) {\n    $currentUser-\u003egetIdentity(); // GuestIdentityInterface instance\n    // Some actions\n}\n```\n\nBoth methods trigger events. Events are of the following classes:\n\n- `Yiisoft\\User\\Event\\BeforeLogin` - triggered at the beginning of login process.\n  Listeners of this event may call `$event-\u003einvalidate()` to cancel the login process.\n- `Yiisoft\\User\\Event\\AfterLogin` - triggered at the ending of login process.\n- `Yiisoft\\User\\Event\\BeforeLogout` - triggered at the beginning of logout process.\n  Listeners of this event may call `$event-\u003einvalidate()` to cancel the logout process.\n- `Yiisoft\\User\\Event\\AfterLogout` - triggered at the ending of logout process.\n\nListeners of these events can get an identity instance participating in the process using `$event-\u003egetIdentity()`.\nEvents are dispatched by `Psr\\EventDispatcher\\EventDispatcherInterface` instance, which is specified in the\nconstructor when the `Yiisoft\\User\\CurrentUser` instance is initialized.\n\n#### Checking user access\n\nTo be able to check whether the current user can perform an operation corresponding to a given permission,\nyou need to set an access checker (see [yiisoft/access](https://github.com/yiisoft/access)) instance:\n\n```php\n/** \n * @var \\Yiisoft\\Access\\AccessCheckerInterface $accessChecker\n */\n \n$currentUser = $currentUser-\u003ewithAccessChecker($accessChecker);\n```\n\nTo perform the check, use `can()` method:\n\n```php\n// The name of the permission (e.g. \"edit post\") that needs access check.\n$permissionName = 'edit-post'; // Required.\n\n// Name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.\n$params = ['postId' =\u003e 42]; // Optional. Default is empty array.\n\nif ($currentUser-\u003ecan($permissionName, $params)) {\n    // Some actions\n}\n```\n\nNote that in case access checker is not provided via `withAccessChecker()` method, `can()` will always return `false`.\n\n#### Session usage\n\nThe current user can store user ID and authentication timeouts for auto-login in the session.\nTo do this, you need to provide a session (see [yiisoft/session](https://github.com/yiisoft/session)) instance:\n\n```php\n/** \n * @var \\Yiisoft\\Session\\SessionInterface $session\n */\n \n$currentUser = $currentUser-\u003ewithSession($session);\n```\n\nYou can set timeout (number of seconds), during which the user will be logged\nout automatically in case of remaining inactive:\n\n```php\n$currentUser = $currentUser-\u003ewithAuthTimeout(3600);\n```\n\nAlso, an absolute timeout (number of seconds) could be used. The user will be logged\nout automatically regardless of activity:\n\n```php\n$currentUser = $currentUser-\u003ewithAbsoluteAuthTimeout(3600);\n```\n\nBy default, timeouts are not used, so the user will be logged out after the current session expires.\n\n#### Using with event loop\n\nThe `Yiisoft\\User\\CurrentUser` instance is stateful, so when you build long-running applications\nwith tools like [Swoole](https://www.swoole.co.uk/) or [RoadRunner](https://roadrunner.dev/) you should reset\nthe state at every request. For this purpose, you can use the `clear()` method.\n\n### Authentication methods\n\nThis package provides two authentication methods, `WebAuth` and `ApiAuth`, that implement the `Yiisoft\\Auth\\AuthenticationMethodInterface`. Both can be provided to the `Yiisoft\\Auth\\Authentication` middleware as authentication method.\n\n#### WebAuth\n\n`WebAuth` is used to authenticate users in the classic web applications.\nIf authentication is failed, it creates a new instance of the response and adds a `Location` header with a temporary redirect to the authentication URL, by default `/login`.\n\nYou can change authentication URL by calling `WebAuth::withAuthUrl()` method:\n\n```php\nuse Yiisoft\\User\\Method\\WebAuth;\n\n$authenticationMethod = new WebAuth();\n\n// Returns a new instance with the specified authentication URL.\n$authenticationMethod = $authenticationMethod-\u003ewithAuthUrl('/auth');\n```\n\nor in the [DI container](https://github.com/yiisoft/di):\n\n```php\n// config/web/di/auth.php\nreturn [\n    WebAuth::class =\u003e [\n        'withAuthUrl()' =\u003e ['/auth'],\n    ],\n];\n```\n\nor through the parameter `authUrl` of the `yiisoft/user` config group, [yiisoft/config](https://github.com/yiisoft/config) package must be installed:\n\n```php\n// config/web/params.php\nreturn [\n    'yiisoft/user' =\u003e [\n        'authUrl' =\u003e '/auth',\n    ],\n];\n```\n\nIf the application is used along with the [yiisoft/config](https://github.com/yiisoft/config), the package is [configured](./config/di-web.php)\nautomatically to use `WebAuth` as default implementation of `Yiisoft\\Auth\\AuthenticationMethodInterface`.\n\n#### ApiAuth\n\n`ApiAuth` is used to authenticate users in the API clients.\nIf authentication is failed, it returns the response from the `Yiisoft\\Auth\\Middleware\\Authentication::authenticationFailureHandler` handler.\n\nTo use `ApiAuth` as an authentication method, you need or provide the `ApiAuth` instance to the `Yiisoft\\Auth\\Middleware\\Authentication` middleware:\n\n```php\nuse Yiisoft\\Auth\\Middleware\\Authentication;\nuse Yiisoft\\User\\Method\\ApiAuth;\n\n$authenticationMethod = new ApiAuth();\n\n$middleware = new Authentication(\n    $authenticationMethod,\n    $responseFactory // PSR-17 ResponseFactoryInterface\n);\n```\n\nof to define it as an implementation of `Yiisoft\\Auth\\AuthenticationMethodInterface` in the [DI container](https://github.com/yiisoft/di) configuration:\n\n```php\n// config/web/di/auth.php\nuse Yiisoft\\Auth\\AuthenticationMethodInterface;\nuse Yiisoft\\User\\Method\\ApiAuth;\n\nreturn [\n    AuthenticationMethodInterface::class =\u003e ApiAuth::class,\n];\n```\n\nFor more information about the authentication middleware and authentication methods, see the [yiisoft/auth](https://github.com/yiisoft/auth).\n\n### Auto login through identity from request attribute\n\nFor auto login, you can use the `Yiisoft\\User\\Login\\LoginMiddleware`. This middleware automatically logs user\nin if `Yiisoft\\Auth\\IdentityInterface` instance presents in a request attribute. It is usually put there by\n`Yiisoft\\Auth\\Middleware\\Authentication`.\n\n\u003e Please note that `Yiisoft\\Auth\\Middleware\\Authentication` should be located before\n\u003e `Yiisoft\\User\\Login\\LoginMiddleware` in the middleware stack.\n\n### Auto login through cookie\n\nIn order to log user in automatically based on request cookie presence,\nuse `Yiisoft\\User\\Login\\Cookie\\CookieLoginMiddleware`.\n\nTo use a middleware, you need to implement `Yiisoft\\User\\Login\\Cookie\\CookieLoginIdentityInterface`\nand also implement and use an instance of `IdentityRepositoryInterface` in the `CurrentUser`,\nwhich will return `CookieLoginIdentityInterface`:\n\n```php\nuse App\\CookieLoginIdentity;\nuse Yiisoft\\Auth\\IdentityRepositoryInterface;\n\nfinal class CookieLoginIdentityRepository implements IdentityRepositoryInterface\n{\n    private Storage $storage;\n\n    public function __construct(Storage $storage)\n    {\n        $this-\u003estorage = $storage;\n    }\n\n    public function findIdentity(string $id): ?Identity\n    {   \n        return new CookieLoginIdentity($this-\u003estorage-\u003efindOne($id));\n    }\n}\n```\n\nThe `CookieLoginMiddleware` will check for the existence of a cookie in the request,\nvalidate it and login the user automatically.\n\n#### Creating a cookie\n\nBy default, you should set cookie for auto login manually in your application after logging user in:\n\n```php\npublic function login(\n    \\Psr\\Http\\Message\\ServerRequestInterface $request,\n    \\Psr\\Http\\Message\\ResponseFactoryInterface $responseFactory,\n    \\Yiisoft\\User\\Login\\Cookie\\CookieLogin $cookieLogin,\n    \\Yiisoft\\User\\CurrentUser $currentUser\n): \\Psr\\Http\\Message\\ResponseInterface {\n    $response = $responseFactory-\u003ecreateResponse();\n    $body = $request-\u003egetParsedBody();\n    \n    // Get user identity based on body content.\n    \n    /** @var \\Yiisoft\\User\\Login\\Cookie\\CookieLoginIdentityInterface $identity */\n    \n    if ($currentUser-\u003elogin($identity) \u0026\u0026 ($body['rememberMe'] ?? false)) {\n        $response = $cookieLogin-\u003eaddCookie($identity, $response);\n    }\n    \n    return $response;\n}\n```\n\nIn the above `rememberMe` in the request body may come from a \"remember me\" checkbox in the form. End user decides\nif he wants to be logged in automatically. If you do not need the user to be able to choose and want to always use\n\"remember me\", you can enable it via the `forceAddCookie` in `params.php`:\n\n```php\nreturn [\n    'yiisoft/user' =\u003e [\n        'authUrl' =\u003e '/login',\n        'cookieLogin' =\u003e [\n            'forceAddCookie' =\u003e true,\n            'duration' =\u003e 'P5D', // 5 days\n        ],\n    ],\n];\n```\n\n\u003e If you want the cookie to be a session cookie, change the duration to `null`.\n\n#### Removing a cookie\n\nThe `Yiisoft\\User\\Login\\Cookie\\CookieLoginMiddleware` automatically removes the cookie after the logout.\nBut you can also remove the cookie manually:\n\n```php\npublic function logout(\n    \\Psr\\Http\\Message\\ResponseFactoryInterface $responseFactory,\n    \\Yiisoft\\User\\Login\\Cookie\\CookieLogin $cookieLogin,\n    \\Yiisoft\\User\\CurrentUser $currentUser\n): \\Psr\\Http\\Message\\ResponseInterface {\n    $response = $responseFactory\n        -\u003ecreateResponse(302)\n        -\u003ewithHeader('Location', '/');\n    \n    // Regenerate cookie login key to `Yiisoft\\User\\Login\\Cookie\\CookieLoginIdentityInterface` instance.\n    \n    if ($currentUser-\u003elogout()) {\n        $response = $cookieLogin-\u003eexpireCookie($response);\n    }\n    \n    return $response;\n}\n```\n\n#### Preventing the substitution of cookies\n\nThe login cookie value is stored raw. To prevent the substitution of the cookie value,\nyou can use a `Yiisoft\\Cookies\\CookieMiddleware`. For more information, see\n[Yii guide to cookies](https://github.com/yiisoft/docs/blob/master/guide/en/runtime/cookies.md).\n\n\u003e Please note that `Yiisoft\\Cookies\\CookieMiddleware` should be located before\n\u003e `Yiisoft\\User\\Login\\Cookie\\CookieLoginMiddleware` in the middleware stack.\n\nYou can find examples of the above features in the [yiisoft/demo](https://github.com/yiisoft/demo).\n\n## Documentation\n\n- [Internals](docs/internals.md)\n\nIf you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for\nthat. You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).\n\n## License\n\nThe Yii User is free software. It is released under the terms of the BSD License.\nPlease see [`LICENSE`](./LICENSE.md) for more information.\n\nMaintained by [Yii Software](https://www.yiiframework.com/).\n\n## Support the project\n\n[![Open Collective](https://img.shields.io/badge/Open%20Collective-sponsor-7eadf1?logo=open%20collective\u0026logoColor=7eadf1\u0026labelColor=555555)](https://opencollective.com/yiisoft)\n\n## Follow updates\n\n[![Official website](https://img.shields.io/badge/Powered_by-Yii_Framework-green.svg?style=flat)](https://www.yiiframework.com/)\n[![Twitter](https://img.shields.io/badge/twitter-follow-1DA1F2?logo=twitter\u0026logoColor=1DA1F2\u0026labelColor=555555?style=flat)](https://twitter.com/yiiframework)\n[![Telegram](https://img.shields.io/badge/telegram-join-1DA1F2?style=flat\u0026logo=telegram)](https://t.me/yii3en)\n[![Facebook](https://img.shields.io/badge/facebook-join-1DA1F2?style=flat\u0026logo=facebook\u0026logoColor=ffffff)](https://www.facebook.com/groups/yiitalk)\n[![Slack](https://img.shields.io/badge/slack-join-1DA1F2?style=flat\u0026logo=slack)](https://yiiframework.com/go/slack)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Fuser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyiisoft%2Fuser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Fuser/lists"}