{"id":15491202,"url":"https://github.com/byjg/php-authuser","last_synced_at":"2025-04-22T19:21:21.576Z","repository":{"id":35815745,"uuid":"40098325","full_name":"byjg/php-authuser","owner":"byjg","description":"A simple and customizable class for enable user authentication inside your application. It is available on XML files, Relational Databases and Moodle.","archived":false,"fork":false,"pushed_at":"2024-10-29T22:10:18.000Z","size":216,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-30T03:38:14.107Z","etag":null,"topics":["authentication","authentication-flow","authentication-strategy","php-sessions","user-storage"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/byjg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"byjg"}},"created_at":"2015-08-03T01:03:27.000Z","updated_at":"2024-10-29T22:10:02.000Z","dependencies_parsed_at":"2024-01-05T22:03:21.608Z","dependency_job_id":"27e1031e-3d01-440e-a992-3eafc62b34bb","html_url":"https://github.com/byjg/php-authuser","commit_stats":null,"previous_names":["byjg/php-authuser","byjg/authuser"],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/byjg%2Fphp-authuser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/byjg%2Fphp-authuser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/byjg%2Fphp-authuser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/byjg%2Fphp-authuser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/byjg","download_url":"https://codeload.github.com/byjg/php-authuser/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250306601,"owners_count":21408927,"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":["authentication","authentication-flow","authentication-strategy","php-sessions","user-storage"],"created_at":"2024-10-02T07:44:17.646Z","updated_at":"2025-04-22T19:21:21.545Z","avatar_url":"https://github.com/byjg.png","language":"PHP","funding_links":["https://github.com/sponsors/byjg"],"categories":[],"sub_categories":[],"readme":"# Auth User PHP\n\n[![Build Status](https://github.com/byjg/php-authuser/actions/workflows/phpunit.yml/badge.svg?branch=master)](https://github.com/byjg/php-authuser/actions/workflows/phpunit.yml)\n[![Opensource ByJG](https://img.shields.io/badge/opensource-byjg-success.svg)](http://opensource.byjg.com)\n[![GitHub source](https://img.shields.io/badge/Github-source-informational?logo=github)](https://github.com/byjg/php-authuser/)\n[![GitHub license](https://img.shields.io/github/license/byjg/php-authuser.svg)](https://opensource.byjg.com/opensource/licensing.html)\n[![GitHub release](https://img.shields.io/github/release/byjg/php-authuser.svg)](https://github.com/byjg/php-authuser/releases/)\n\nA simple and customizable class for enable user authentication inside your application. It is available on XML files, Relational Databases.\n\nThe main purpose is just to handle all complexity of validate a user, add properties and create access token abstracting the database layer.\nThis class can persist into session (or file, memcache, etc) the user data between requests.\n\n## Creating a Users handling class\n\nUsing the FileSystem (XML) as the user storage:\n\n```php\n\u003c?php\n$users = new UsersAnyDataset('/tmp/pass.anydata.xml');\n```\n\nUsing the Database as the user storage:\n\n```php\n\u003c?php\n$users = new ByJG\\Authenticate\\UsersDBDataset(\n    'connection',   // The connection string. Please refer to the project byjg/anydataset\n    new UserDefinition(),  // The field metadata for store the users\n    new UserPropertiesDefinition()  // The field metadata for store the extra properties\n);\n```\n\n*Note*: See the [Anydataset project](https://github.com/byjg/anydataset#connection-based-on-uri) to see the\ndatabase available and the connection strings as well.\n\n## Check if user was previously authenticated\n\n```php\n\u003c?php\n$sessionContext = new \\ByJG\\Authenticate\\SessionContext(\\ByJG\\Cache\\Factory::createSessionPool());\n\n// Check if the user is authenticated\nif ($sessionContext-\u003eisAuthenticated()) {\n\n    // Get the userId of the authenticated users\n    $userId = $sessionContext-\u003euserInfo();\n\n    // Get the user and your name\n    $user = $users-\u003egetById($userId);\n    echo \"Hello: \" . $user-\u003egetName();\n}\n```\n\n## Saving extra info into the user session\n\nYou can save data in the session data exists only during the user is logged in. Once the user logged off the\ndata stored with the user session will be released.\n\nStore the data for the current user session:\n\n```php\n\u003c?php\n$sessionContext = new \\ByJG\\Authenticate\\SessionContext(\\ByJG\\Cache\\Factory::createSessionPool());\n$sessionContext-\u003esetSessionData('key', 'value');\n```\n\nGetting the data from the current user session:\n\n```php\n\u003c?php\n$sessionContext = new \\ByJG\\Authenticate\\SessionContext(\\ByJG\\Cache\\Factory::createSessionPool());\n$value = $sessionContext-\u003egetSessionData('key');\n```\n\nNote: If the user is not logged an error will be throw\n\n## Adding a custom property to the users\n\n```php\n\u003c?php\n$user = $users-\u003egetById($userId);\n$user-\u003esetField('somefield', 'somevalue');\n$users-\u003esave();\n```\n\n## Logout from a session\n\n```php\n\u003c?php\n$sessionContext-\u003eregisterLogout();\n```\n\n## Important note about SessionContext\n\n`SessionContext` object will store the info about the current context.\nAs SessionContext uses CachePool interface defined in PSR-6 you can set any storage\nto save your session context.\n\nIn our examples we are using a regular PHP Session for store the user context\n(`Factory::createSessionPool()`). But if you are using another store like MemCached\nyou have to define a UNIQUE prefix for that session. Note if TWO users have the same\nprefix you probably have an unexpected result for the SessionContext.\n\nExample for memcached:\n\n```php\n\u003c?php\n$sessionContext = new \\ByJG\\Authenticate\\SessionContext(\\ByJG\\Cache\\Factory::createMemcachedPool(), 'UNIQUEPREFIX');\n```\n\nIf you do not know to create/manage that unique prefix **prefer to use the regular Session object.**\n\n## Architecture\n\n```text\n                                   ┌───────────────────┐\n                                   │  SessionContext   │\n                                   └───────────────────┘\n                                             │\n┌────────────────────────┐                                       ┌────────────────────────┐\n│     UserDefinition     │─ ─ ┐              │               ─ ─ ┤       UserModel        │\n└────────────────────────┘         ┌───────────────────┐    │    └────────────────────────┘\n┌────────────────────────┐    └────│  UsersInterface   │────┐    ┌────────────────────────┐\n│ UserPropertyDefinition │─ ─ ┘    └───────────────────┘     ─ ─ ┤   UserPropertyModel    │\n└────────────────────────┘                   ▲                   └────────────────────────┘\n                                             │\n                    ┌────────────────────────┼─────────────────────────┐\n                    │                        │                         │\n                    │                        │                         │\n                    │                        │                         │\n          ┌───────────────────┐    ┌───────────────────┐    ┌────────────────────┐\n          │  UsersAnyDataset  │    │  UsersDBDataset   │    │ xxxxxxxxxxxxxxxxxx │\n          └───────────────────┘    └───────────────────┘    └────────────────────┘\n```\n\n- UserInterface contain the basic interface for the concrete implementation\n- UsersDBDataset is a concrete implementation to retrieve/save user in a Database\n- UserAnyDataset is a concrete implementation to retrieve/save user in a Xml file\n- UserModel is the basic model get/set for the user\n- UserPropertyModel is the basic model get/set for extra user property\n- UserDefinition will map the model to the database\n\n### Database\n\nThe default structure adopted for store the user data in the database through the\nUsersDBDataset class is the follow:\n\n```sql\ncreate table users\n(\n    userid integer AUTO_INCREMENT not null,\n    name varchar(50),\n    email varchar(120),\n    username varchar(15) not null,\n    password char(40) not null,\n    created datetime,\n    admin enum('Y','N'),\n\n    constraint pk_users primary key (userid)\n)\nENGINE=InnoDB;\n\ncreate table users_property\n(\n   customid integer AUTO_INCREMENT not null,\n   name varchar(20),\n   value varchar(100),\n   userid integer not null,\n\n   constraint pk_custom primary key (customid),\n   constraint fk_custom_user foreign key (userid) references users (userid)\n)\nENGINE=InnoDB;\n```\n\nUsing the database structure above you can create the UsersDBDatase as follow:\n\n```php\n\u003c?php\n$users = new ByJG\\Authenticate\\UsersDBDataset(\n    'connection',\n    new \\ByJG\\Authenticate\\Definition\\UserDefinition(),\n    new \\ByJG\\Authenticate\\Definition\\UserPropertiesDefinition()\n);\n```\n\n### Custom Database\n\nIf you have an existing database with different names but containing all fields above\nyou can use the UserDefinition and UserPropertiesDefinition classes for customize this info.\n\n```php\n\u003c?php\n$userDefinition = new \\ByJG\\Authenticate\\Definition\\UserDefinition(\n    'users',    // $table\n    \\ByJG\\Authenticate\\Model\\UserModel::class, // Model class\n    \\ByJG\\Authenticate\\Definition\\UserDefinition::LOGIN_IS_EMAIL,\n    [\n        UserDefinition::FIELD_USERID   =\u003e 'fieldname of userid',\n        UserDefinition::FIELD_NAME     =\u003e 'fieldname of name',\n        UserDefinition::FIELD_EMAIL    =\u003e 'fieldname of email',\n        UserDefinition::FIELD_USERNAME =\u003e 'fieldname of username',\n        UserDefinition::FIELD_PASSWORD =\u003e 'fieldname of password',\n        UserDefinition::FIELD_CREATED  =\u003e 'fieldname of created',\n        UserDefinition::FIELD_ADMIN    =\u003e 'fieldname of admin'\n    ]\n);\n```\n\n### Adding custom modifiers for read and update\n\n```php\n\u003c?php\n$userDefinition = new \\ByJG\\Authenticate\\Definition\\UserDefinition(\n    'users',    // $table\n    \\ByJG\\Authenticate\\Model\\User::class,\n    \\ByJG\\Authenticate\\Definition\\UserDefinition::LOGIN_IS_EMAIL\n);\n\n// Defines a custom function to be applied BEFORE update/insert the field UserDefinition::FIELD_PASSWORD\n// $value --\u003e the current value to be updated\n// $instance -\u003e The array with all other fields;\n$userDefinition-\u003edefineClosureForUpdate(UserDefinition::FIELD_PASSWORD, function ($value, $instance) {\n    return strtoupper(sha1($value));\n});\n\n// Defines a custom function to be applied After the field UserDefinition::FIELD_CREATED is read but before\n// the user get the result\n// $value --\u003e the current value retrieved from database\n// $instance -\u003e The array with all other fields;\n$userDefinition-\u003edefineClosureForSelect(UserDefinition::FIELD_CREATED, function ($value, $instance) {\n    return date('Y', $value);\n});\n\n// If you want make the field READONLY just do it:\n$userDefinition-\u003emarkPropertyAsReadOnly(UserDefinition::FIELD_CREATED);\n```\n\n## Extending UserModel\n\nIt is possible extending the UserModel table, since you create a new class extending from UserModel to add the new fields.\n\nFor example, imagine your table has one field called \"otherfield\".\n\nYou'll have to extend like this:\n\n```php\n\u003c?php\n/**\n * This class is your model\n * This need to support the basic field plus your new fields\n * already set in your definition class\n */\nclass MyUserModel extends UserModel\n{\n    protected $otherfield;\n\n    public function __construct($name = \"\", $email = \"\", $username = \"\", $password = \"\", $admin = \"no\", $field = \"\")\n    {\n        parent::__construct($name, $email, $username, $password, $admin);\n        $this-\u003esetOtherfield($field);\n    }\n\n    public function getOtherfield()\n    {\n        return $this-\u003eotherfield;\n    }\n\n    public function setOtherfield($otherfield)\n    {\n        $this-\u003eotherfield = $otherfield;\n    }\n}\n```\n\nAfter that you can use your new definition:\n\n```php\n\u003c?php\n$users = new ByJG\\Authenticate\\UsersDBDataset(\n    'connection',\n    new \\ByJG\\Authenticate\\Definition\\UserDefinition(\n        'tablename',\n        MyUserModel::class,\n        UserDefinition::LOGIN_IS_EMAIL\n    ),\n    new \\ByJG\\Authenticate\\Definition\\UserPropertiesDefinition()\n);\n```\n\n## Install\n\nJust type:\n\n```bash\ncomposer require \"byjg/authuser\"\n```\n\n## Running Tests\n\nBecause this project uses PHP Session you need to run the unit test the following manner:\n\n```bash\n./vendor/bin/phpunit --stderr\n```\n\n## Dependencies\n\n```mermaid  \nflowchart TD  \n    byjg/authuser --\u003e byjg/micro-orm\n    byjg/authuser --\u003e byjg/cache-engine\n    byjg/authuser --\u003e byjg/jwt-wrapper  \n```\n\n\n----\n[Open source ByJG](http://opensource.byjg.com)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbyjg%2Fphp-authuser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbyjg%2Fphp-authuser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbyjg%2Fphp-authuser/lists"}