{"id":16423568,"url":"https://github.com/rougin/authsum","last_synced_at":"2025-04-14T09:13:39.445Z","repository":{"id":62537477,"uuid":"106781106","full_name":"rougin/authsum","owner":"rougin","description":"Simple authentication package in PHP.","archived":false,"fork":false,"pushed_at":"2024-11-18T15:25:06.000Z","size":108,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-14T09:13:29.318Z","etag":null,"topics":["auth-logic","php-auth","php-login"],"latest_commit_sha":null,"homepage":"https://roug.in/authsum/","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/rougin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-10-13T05:20:38.000Z","updated_at":"2024-11-18T15:25:21.000Z","dependencies_parsed_at":"2022-11-02T15:16:19.404Z","dependency_job_id":null,"html_url":"https://github.com/rougin/authsum","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rougin%2Fauthsum","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rougin%2Fauthsum/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rougin%2Fauthsum/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rougin%2Fauthsum/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rougin","download_url":"https://codeload.github.com/rougin/authsum/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248852182,"owners_count":21171842,"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":["auth-logic","php-auth","php-login"],"created_at":"2024-10-11T07:40:18.473Z","updated_at":"2025-04-14T09:13:39.409Z","avatar_url":"https://github.com/rougin.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Authsum\n\n[![Latest Version on Packagist][ico-version]][link-packagist]\n[![Software License][ico-license]][link-license]\n[![Build Status][ico-build]][link-build]\n[![Coverage Status][ico-coverage]][link-coverage]\n[![Total Downloads][ico-downloads]][link-downloads]\n\n`Authsum` is a simple authentication package written in PHP which allows to create simple and extensible authentication logic.\n\n## Installation\n\nInstall the `Authsum` package via [Composer](https://getcomposer.org/):\n\n``` bash\n$ composer require rougin/authsum\n```\n\n## Basic usage\n\nPrior in using `Authsum`, a data source must be defined first (e.g., `BasicSource`):\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Source\\BasicSource;\n\n// ...\n\n$username = 'admin';\n$password = /** ... */;\n\n// Check if the provided username and password data ---\n// matched from the given payload (e.g., $_POST) ------\n$source = new BasicSource($username, $password);\n// ----------------------------------------------------\n\n// ...\n```\n\nOnce the source is defined, use the `Authsum` class to perform the validation logic:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Authsum;\n\n// ...\n\n$auth = new Authsum($source);\n\nif ($auth-\u003eisValid($_POST))\n{\n    /** @var \\Acme\\Models\\User */\n    $user = $auth-\u003egetResult()-\u003egetField('user');\n\n    echo 'Welcome ' . $user-\u003egetName() . '!';\n}\nelse\n{\n    echo 'Invalid credentials!';\n}\n```\n\n## Customization\n\n`Authsum` also provides simple extensibility utilities to be able to fit in from various use-cases.\n\n### Pass or fail from `Authsum`\n\nThe `Authsum` class can also be extended to provide methods if the validation logic passed or failed:\n\n``` php\nnamespace Acme;\n\nuse Acme\\Depots\\AuditDepot;\nuse Acme\\Errors\\NoAccount;\nuse Rougin\\Authsum\\Authsum;\nuse Rougin\\Authsum\\Error;\nuse Rougin\\Authsum\\Result;\n\nclass TestAuth extends Authsum\n{\n    protected $audit;\n\n    public function __construct(AuditDepot $audit)\n    {\n        $this-\u003eaudit = $audit;\n    }\n\n    /**\n     * Executes if the validation failed.\n     *\n     * @param \\Rougin\\Authsum\\Error $error\n     *\n     * @return void\n     */\n    protected function failed(Error $error)\n    {\n        throw new NoAccount($error-\u003egetText());\n    }\n\n    /**\n     * Executes if the validation passed.\n     *\n     * @param \\Rougin\\Authsum\\Result $data\n     *\n     * @return void\n     */\n    protected function passed(Result $data)\n    {\n        /** @var string */\n        $user = $data-\u003egetField('name');\n\n        $this-\u003eaudit-\u003euserLoggedIn($user);\n    }\n}\n```\n\nAlternatively, the `Authsum` class can also get the error or the result after validation using `getError()` and `getResult()` respectively:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Authsum;\n\n// ...\n\n$auth = new Authsum($source);\n\nif ($auth-\u003eisValid($_POST))\n{\n    $result = $auth-\u003egetResult();\n\n    /** @var string */\n    $name = $result-\u003egetField('name');\n\n    echo 'Welcome ' . $name . '!';\n}\nelse\n{\n    $error = $auth-\u003egetError();\n\n    echo 'Error: ' . $auth-\u003egetText();\n}\n```\n\n\u003e [!NOTE]\n\u003e An `UnexpectedValueException` will be thrown if trying to access an empty output (e.g., trying to access `getResult()` after the failed validation).\n\n### Changing fields to check\n\nBy default, the `Authsum` class can check the `email` as its username and `password` for the password from the payload (e.g., `$_POST`). If this is not the case, kindly update the specified fields using `setUsernameField` or `setPasswordField`:\n\n``` php\n// index.php\n\n// ...\n\n$auth-\u003esetUsernameField('username');\n$auth-\u003esetPasswordField('password');\n\n// ...\n```\n\n\u003e [!NOTE]\n\u003e The specified fields will be used by the `Authsum` class if they are required by the specified source (e.g., `BasicSource`, `PdoSource`).\n\n### Using sources\n\nSources in `Authsum` are PHP classes that provide user data. They can be used for checking the specified username and password fields against its data source:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Authsum;\nuse Rougin\\Authsum\\Source\\BasicSource;\n\n// ...\n\n// Initialize the source... --------------------\n$username = 'admin';\n$password = /** ... */;\n\n$source = new BasicSource($username, $password);\n// ---------------------------------------------\n\n// ...then pass it to Authsum ---\n$auth = new Authsum($source);\n// ------------------------------\n\n// The source will be used to check if ---\n// the provided payload matches in the ---\n// given payload ($_POST) from its source\n$valid = $auth-\u003eisValid($_POST);\n// ---------------------------------------\n\n// ...\n```\n\n#### `PdoSource`\n\nBesides from `BasicSource`, another available source that can be used is `PdoSource` which uses [PDO](https://www.php.net/manual/en/intro.pdo.php) to interact with a database:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Source\\PdoSource;\n\n// ...\n\n// Create a PDO instance... --------------\n$dsn = 'mysql:host=localhost;dbname=demo';\n\n$pdo = new PDO($dsn, 'root', /** ... */);\n// ---------------------------------------\n\n// ...then pass it to the PdoSource ---\n$source = new PdoSource($pdo);\n// ------------------------------------\n\n// ...\n```\n\nThe `setTableName` method can also be used to specify its database table name:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Source\\PdoSource;\n\n// ...\n\n$source = new PdoSource($pdo);\n\n$source-\u003esetTableName('users');\n\n// ...\n```\n\n\u003e [!NOTE]\n\u003e If the `setTableName` is not specified, it always refer to the `users` table.\n\nWhen using `PdoSource`, the value in the `password` field will be assumed as a hash (e.g., `$2y$10...`). If this is not the case, kindly add the `withoutHash` method:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Source\\PdoSource;\n\n// ...\n\n$source = new PdoSource($pdo);\n\n$source-\u003ewithoutHash();\n\n// ...\n```\n\nDoing this will make a strict comparison of the provided `password` against the result from the database.\n\n#### `JwtSource`\n\nThe `JwtSource` class is a special class that checks a user's authentication using [JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token):\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Source\\JwtSource;\n\n// ...\n\n/** @var \\Rougin\\Authsum\\Source\\JwtParserInterface */\n$parser = /** ... */;\n\n$source = new JwtSource($parser);\n```\n\nFrom the example above, initializing `JwtSource` requires a `JwtParserInterface` for parsing the JSON web tokens from payload:\n\n``` php\nnamespace Rougin\\Authsum\\Source;\n\ninterface JwtParserInterface\n{\n    /**\n     * Parses the token string.\n     *\n     * @param string $token\n     *\n     * @return array\u003cstring, mixed\u003e\n     */\n    public function parse($token);\n}\n```\n\nIf `JwtSource` is used as a source, the `token` field must be updated also from the `Authsum` class based on the query parameter or parsed body where the token exists:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Authsum;\nuse Rougin\\Authsum\\Source\\JwtSource;\n\n// ...\n\n$source = new JwtSource($parser);\n\n// Search \"token\" property from the payload ---\n$source-\u003esetTokenField('token');\n// --------------------------------------------\n\n$auth = new Authsum($source);\n```\n\n\u003e [!NOTE]\n\u003e If `setTokenField` is not specified, its default value is `token`.\n\nThen use the `setUsernameField` to specify the field to be compared against the parsed data from the JSON web token:\n\n``` php\n// index.php\n\nuse Rougin\\Authsum\\Authsum;\n\n// ...\n\n$auth = new Authsum($source);\n\n// ...\n\n$auth-\u003esetUsernameField('email');\n\n// The $_POST data should contains the ---\n// \"token\" field and the \"email\" field ---\n$valid = $auth-\u003eisValid($_POST);\n// ---------------------------------------\n```\n\n### Creating custom sources\n\nTo create a custom source, kindly use the `SourceInterface` for its implementation:\n\n``` php\nnamespace Rougin\\Authsum\\Source;\n\ninterface SourceInterface\n{\n    /**\n     * Returns the error after validation.\n     *\n     * @return \\Rougin\\Authsum\\Error\n     */\n    public function getError();\n\n    /**\n     * Returns the result after validation.\n     *\n     * @return \\Rougin\\Authsum\\Result\n     */\n    public function getResult();\n\n    /**\n     * Checks if it exists from the source.\n     *\n     * @return boolean\n     */\n    public function isValid();\n}\n```\n\nIf the custom source requires an `username` field, kindly add the `WithUsername` interface:\n\n``` php\nnamespace Rougin\\Authsum\\Source;\n\ninterface WithUsername\n{\n    /**\n     * Sets the username field.\n     *\n     * @param string $username\n     *\n     * @return self\n     */\n    public function setUsernameField($username);\n\n    /**\n     * Sets the username.\n     *\n     * @param string $username\n     *\n     * @return self\n     */\n    public function setUsernameValue($username);\n}\n```\n\nThe `WithPassword` interface can be also added if the custom source requires a password to be defined:\n\n``` php\nnamespace Rougin\\Authsum\\Source;\n\ninterface WithPassword\n{\n    /**\n     * Sets the password field.\n     *\n     * @param string $password\n     *\n     * @return self\n     */\n    public function setPasswordField($password);\n\n    /**\n     * Sets the password value.\n     *\n     * @param string $password\n     *\n     * @return self\n     */\n    public function setPasswordValue($password);\n}\n```\n\nSome custom sources may require to use the provided payload instead of `username` and `password` fields (e.g., `JwtSource`). With this, kindly use the `WithPayload` interface:\n\n``` php\nnamespace Rougin\\Authsum\\Source;\n\ninterface WithPayload\n{\n    /**\n     * Sets the prepared payload.\n     *\n     * @param array\u003cstring, string\u003e $payload\n     *\n     * @return self\n     */\n    public function setPayload($payload);\n}\n```\n\n## Testing\n\nIf there is a need to check the source code of `Authsum` for development purposes (e.g., creating fixes, new features, etc.), kindly clone this repository first to a local machine:\n\n``` bash\n$ git clone https://github.com/rougin/authsum.git \"Sample\"\n```\n\nAfter cloning, use `Composer` to install its required packages:\n\n``` bash\n$ cd Sample\n$ composer update\n```\n\n\u003e [!NOTE]\n\u003e Please see also the [build.yml](https://github.com/rougin/authsum/blob/master/.github/workflows/build.yml) of `Authsum` to check any packages that needs to be installed based on the PHP version.\n\nOnce the required packages were installed, kindly check the following below on how to maintain the code quality and styling guide when interacting the source code of `Authsum`:\n\n### Unit tests\n\n`Authsum` also contains unit tests that were written in [PHPUnit](https://phpunit.de/index.html):\n\n``` bash\n$ composer test\n```\n\nWhen creating fixes or implementing new features, it is recommended to run the above command to always check if the updated code introduces errors during development.\n\n### Code quality\n\nTo retain the code quality of `Authsum`, a static code analysis code tool named [PHPStan](https://phpstan.org/) is being used during development. To start, kindly install the specified package in the global environment of `Composer`:\n\n``` bash\n$ composer global require phpstan/phpstan --dev\n```\n\nOnce installed, `PHPStan` can now be run using its namesake command:\n\n``` bash\n$ cd Sample\n$ phpstan\n```\n\n\u003e [!NOTE]\n\u003e When running `phpstan`, it will use the `phpstan.neon` file which is already provided by `Authsum`.\n\n### Coding style\n\nAside from code quality, `Authsum` also uses a tool named [PHP Coding Standards Fixer](https://cs.symfony.com/) for maintaining an opinionated style guide. To use this tooling, it needs also to be installed in the `Composer`'s global environment first:\n\n``` bash\n$ composer global require friendsofphp/php-cs-fixer --dev\n```\n\nAfter its installation, kindly use the `php-cs-fixer` command in the same `Authsum` directory:\n\n``` bash\n$ cd Sample\n$ php-cs-fixer fix --config=phpstyle.php\n```\n\nThe `phpstyle.php` file provided by `Authsum` currently follows the [PSR-12](https://www.php-fig.org/psr/psr-12/) standard as its baseline for the coding style and uses [Allman](https://en.wikipedia.org/wiki/Indentation_style#Allman_style) as its indentation style.\n\n\u003e [!NOTE]\n\u003e Installing both `PHPStan` and `PHP Coding Standards Fixer` requires a minimum version of PHP at least `7.4`.\n\n## Changelog\n\nPlease see [CHANGELOG][link-changelog] for more information what has changed recently.\n\n## License\n\nThe MIT License (MIT). Please see [LICENSE][link-license] for more information.\n\n[ico-build]: https://img.shields.io/github/actions/workflow/status/rougin/authsum/build.yml?style=flat-square\n[ico-coverage]: https://img.shields.io/codecov/c/github/rougin/authsum?style=flat-square\n[ico-downloads]: https://img.shields.io/packagist/dt/rougin/authsum.svg?style=flat-square\n[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square\n[ico-version]: https://img.shields.io/packagist/v/rougin/authsum.svg?style=flat-square\n\n[link-build]: https://github.com/rougin/authsum/actions\n[link-changelog]: https://github.com/rougin/authsum/blob/master/CHANGELOG.md\n[link-contributors]: https://github.com/rougin/authsum/contributors\n[link-coverage]: https://app.codecov.io/gh/rougin/authsum\n[link-downloads]: https://packagist.org/packages/rougin/authsum\n[link-license]: https://github.com/rougin/authsum/blob/master/LICENSE.md\n[link-packagist]: https://packagist.org/packages/rougin/authsum","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frougin%2Fauthsum","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frougin%2Fauthsum","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frougin%2Fauthsum/lists"}