2017 © Pedro Peláez
 

library authsum

Yet another PHP authentication library.

image

rougin/authsum

Yet another PHP authentication library.

  • Tuesday, July 31, 2018
  • by rougin
  • Repository
  • 1 Watchers
  • 1 Stars
  • 160 Installations
  • PHP
  • 1 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 332 % Grown

The README.md

Authsum

Latest Version on Packagist ![Software License][ico-license] Build Status ![Coverage Status][ico-coverage] Total Downloads, (*1)

Authsum is a simple authentication package written in PHP which allows to create simple and extensible authentication logic., (*2)

Installation

Install the Authsum package via Composer:, (*3)

``` bash $ composer require rougin/authsum, (*4)


## Basic usage Prior in using `Authsum`, a data source must be defined first (e.g., `BasicSource`): ``` php // index.php use Rougin\Authsum\Source\BasicSource; // ... $username = 'admin'; $password = /** ... */; // Check if the provided username and password data --- // matched from the given payload (e.g., $_POST) ------ $source = new BasicSource($username, $password); // ---------------------------------------------------- // ...

Once the source is defined, use the Authsum class to perform the validation logic:, (*5)

``` php // index.php, (*6)

use Rougin\Authsum\Authsum;, (*7)

// ..., (*8)

$auth = new Authsum($source);, (*9)

if ($auth->isValid($_POST)) { /** @var \Acme\Models\User */ $user = $auth->getResult()->getField('user');, (*10)

echo 'Welcome ' . $user->getName() . '!';

} else { echo 'Invalid credentials!'; }, (*11)


## Customization `Authsum` also provides simple extensibility utilities to be able to fit in from various use-cases. ### Pass or fail from `Authsum` The `Authsum` class can also be extended to provide methods if the validation logic passed or failed: ``` php namespace Acme; use Acme\Depots\AuditDepot; use Acme\Errors\NoAccount; use Rougin\Authsum\Authsum; use Rougin\Authsum\Error; use Rougin\Authsum\Result; class TestAuth extends Authsum { protected $audit; public function __construct(AuditDepot $audit) { $this->audit = $audit; } /** * Executes if the validation failed. * * @param \Rougin\Authsum\Error $error * * @return void */ protected function failed(Error $error) { throw new NoAccount($error->getText()); } /** * Executes if the validation passed. * * @param \Rougin\Authsum\Result $data * * @return void */ protected function passed(Result $data) { /** @var string */ $user = $data->getField('name'); $this->audit->userLoggedIn($user); } }

Alternatively, the Authsum class can also get the error or the result after validation using getError() and getResult() respectively:, (*12)

``` php // index.php, (*13)

use Rougin\Authsum\Authsum;, (*14)

// ..., (*15)

$auth = new Authsum($source);, (*16)

if ($auth->isValid($_POST)) { $result = $auth->getResult();, (*17)

/** @var string */
$name = $result->getField('name');

echo 'Welcome ' . $name . '!';

} else { $error = $auth->getError();, (*18)

echo 'Error: ' . $auth->getText();

}, (*19)


> [!NOTE] > An `UnexpectedValueException` will be thrown if trying to access an empty output (e.g., trying to access `getResult()` after the failed validation). ### Changing fields to check By 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`: ``` php // index.php // ... $auth->setUsernameField('username'); $auth->setPasswordField('password'); // ...

[!NOTE] The specified fields will be used by the Authsum class if they are required by the specified source (e.g., BasicSource, PdoSource)., (*20)

Using sources

Sources 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:, (*21)

``` php // index.php, (*22)

use Rougin\Authsum\Authsum; use Rougin\Authsum\Source\BasicSource;, (*23)

// ..., (*24)

// Initialize the source... -------------------- $username = 'admin'; $password = /** ... */;, (*25)

$source = new BasicSource($username, $password); // ---------------------------------------------, (*26)

// ...then pass it to Authsum --- $auth = new Authsum($source); // ------------------------------, (*27)

// The source will be used to check if --- // the provided payload matches in the --- // given payload ($_POST) from its source $valid = $auth->isValid($_POST); // ---------------------------------------, (*28)

// ..., (*29)


#### `PdoSource` Besides 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: ``` php // index.php use Rougin\Authsum\Source\PdoSource; // ... // Create a PDO instance... -------------- $dsn = 'mysql:host=localhost;dbname=demo'; $pdo = new PDO($dsn, 'root', /** ... */); // --------------------------------------- // ...then pass it to the PdoSource --- $source = new PdoSource($pdo); // ------------------------------------ // ...

The setTableName method can also be used to specify its database table name:, (*30)

``` php // index.php, (*31)

use Rougin\Authsum\Source\PdoSource;, (*32)

// ..., (*33)

$source = new PdoSource($pdo);, (*34)

$source->setTableName('users');, (*35)

// ..., (*36)


> [!NOTE] > If the `setTableName` is not specified, it always refer to the `users` table. When 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: ``` php // index.php use Rougin\Authsum\Source\PdoSource; // ... $source = new PdoSource($pdo); $source->withoutHash(); // ...

Doing this will make a strict comparison of the provided password against the result from the database., (*37)

JwtSource

The JwtSource class is a special class that checks a user's authentication using JSON Web Token:, (*38)

``` php // index.php, (*39)

use Rougin\Authsum\Source\JwtSource;, (*40)

// ..., (*41)

/** @var \Rougin\Authsum\Source\JwtParserInterface */ $parser = /** ... */;, (*42)

$source = new JwtSource($parser);, (*43)


From the example above, initializing `JwtSource` requires a `JwtParserInterface` for parsing the JSON web tokens from payload: ``` php namespace Rougin\Authsum\Source; interface JwtParserInterface { /** * Parses the token string. * * @param string $token * * @return array<string, mixed> */ public function parse($token); }

If 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:, (*44)

``` php // index.php, (*45)

use Rougin\Authsum\Authsum; use Rougin\Authsum\Source\JwtSource;, (*46)

// ..., (*47)

$source = new JwtSource($parser);, (*48)

// Search "token" property from the payload --- $source->setTokenField('token'); // --------------------------------------------, (*49)

$auth = new Authsum($source);, (*50)


> [!NOTE] > If `setTokenField` is not specified, its default value is `token`. Then use the `setUsernameField` to specify the field to be compared against the parsed data from the JSON web token: ``` php // index.php use Rougin\Authsum\Authsum; // ... $auth = new Authsum($source); // ... $auth->setUsernameField('email'); // The $_POST data should contains the --- // "token" field and the "email" field --- $valid = $auth->isValid($_POST); // ---------------------------------------

Creating custom sources

To create a custom source, kindly use the SourceInterface for its implementation:, (*51)

``` php namespace Rougin\Authsum\Source;, (*52)

interface SourceInterface { /** * Returns the error after validation. * * @return \Rougin\Authsum\Error */ public function getError();, (*53)

/**
 * Returns the result after validation.
 *
 * @return \Rougin\Authsum\Result
 */
public function getResult();

/**
 * Checks if it exists from the source.
 *
 * @return boolean
 */
public function isValid();

}, (*54)


If the custom source requires an `username` field, kindly add the `WithUsername` interface: ``` php namespace Rougin\Authsum\Source; interface WithUsername { /** * Sets the username field. * * @param string $username * * @return self */ public function setUsernameField($username); /** * Sets the username. * * @param string $username * * @return self */ public function setUsernameValue($username); }

The WithPassword interface can be also added if the custom source requires a password to be defined:, (*55)

``` php namespace Rougin\Authsum\Source;, (*56)

interface WithPassword { /** * Sets the password field. * * @param string $password * * @return self */ public function setPasswordField($password);, (*57)

/**
 * Sets the password value.
 *
 * @param string $password
 *
 * @return self
 */
public function setPasswordValue($password);

}, (*58)


Some 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: ``` php namespace Rougin\Authsum\Source; interface WithPayload { /** * Sets the prepared payload. * * @param array<string, string> $payload * * @return self */ public function setPayload($payload); }

Testing

If 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:, (*59)

``` bash $ git clone https://github.com/rougin/authsum.git "Sample", (*60)


After cloning, use `Composer` to install its required packages: ``` bash $ cd Sample $ composer update

[!NOTE] Please see also the build.yml of Authsum to check any packages that needs to be installed based on the PHP version., (*61)

Once 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:, (*62)

Unit tests

Authsum also contains unit tests that were written in PHPUnit:, (*63)

``` bash $ composer test, (*64)


When 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. ### Code quality To 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`: ``` bash $ composer global require phpstan/phpstan --dev

Once installed, PHPStan can now be run using its namesake command:, (*65)

``` bash $ cd Sample $ phpstan, (*66)


> [!NOTE] > When running `phpstan`, it will use the `phpstan.neon` file which is already provided by `Authsum`. ### Coding style Aside 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: ``` bash $ composer global require friendsofphp/php-cs-fixer --dev

After its installation, kindly use the php-cs-fixer command in the same Authsum directory:, (*67)

bash $ cd Sample $ php-cs-fixer fix --config=phpstyle.php, (*68)

The phpstyle.php file provided by Authsum currently follows the PSR-12 standard as its baseline for the coding style and uses Allman as its indentation style., (*69)

[!NOTE] Installing both PHPStan and PHP Coding Standards Fixer requires a minimum version of PHP at least 7.4., (*70)

Changelog

Please see CHANGELOG for more information what has changed recently., (*71)

License

The MIT License (MIT). Please see LICENSE for more information., (*72)

The Versions

31/07 2018

dev-master

9999999-dev

Yet another PHP authentication library.

  Sources   Download

MIT

The Requires

  • php >=5.3.0

 

The Development Requires

authentication php-library simple auth authsum