diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -50,6 +50,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..2763b9c 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} diff --git a/.gitignore b/.gitignore index c1ae9d9..3f47298 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,5 @@ crashlytics.properties crashlytics-build.properties fabric.properties .phpunit.result.cache +.phpunit.cache .phpcs-cache diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index a3a8278..112fd9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,65 +1,212 @@ +# Changelog + +## 3.0.0 - 2026-11-30 + +### Changed + +- `Dot\Authentication\Exception\ExceptionInterface` extends `Throwable`. +- `AuthenticationResult::setIdentity()` accepts `null` to clear the identity. +- `AuthenticationResult` constants have the type `int`. +- `UnauthorizedException::__construct()` accepts any `Throwable` as `$previous`. +- PHPStan runs at level 8. +- Tests use PHPUnit 12 and a real identity fixture instead of mocks. +- PHPUnit fails on all issues: notices, warnings, deprecations and risky tests. +- The 2.x line gets only security fixes. + +### Added + +- Support for PHP 8.6. +- Documentation for v3. +- Upgrade guide from 2.x. + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.2. + +### Fixed + +- `InvalidArgumentExceptionTest` tests the package class instead of the SPL class. + +## 2.7.0 - 2025-10-31 + +### Added + +- Support for PHP 8.4 and 8.5. + +### Removed + +- Support for PHP 8.1. + +### Fixed + +- PHPStan badges. + +## 2.6.0 - 2025-03-05 + +### Changed + +- Replaced Psalm with PHPStan. + +## 2.5.1 - 2025-01-27 + +### Changed + +- Codecov runs on PHP 8.4. +- Psalm 6.x. + +## 2.5.0 - 2025-01-23 + +### Added + +- Support for PHP 8.4. +- `.laminas-ci.json`. + +## 2.4.0 - 2024-05-03 + +### Added + +- Documentation for v2. +- More tests. + +### Fixed + +- Errors in `README.md` and `usage.md`. + +## 2.3.4 - 2023-12-04 + +### Added + +- Support for PHP 8.3. + +## 2.3.3 - 2023-10-11 + +### Changed + +- Return type of `IdentityInterface::getId()`. + +## 2.3.2 - 2023-08-21 + +### Changed + +- Allow `psr/http-message` 2.x. + +### Fixed + +- Codecov configuration. +- A return type. + +## 2.3.1 - 2023-08-17 + +### Changed + +- Type hints and access modifiers. + +### Added + +- Static analysis badges. + +## 2.3.0 - 2023-07-18 + +### Added + +- Unit tests, PHPCS, static analysis and the test GitHub Actions. + +### Changed + +- Line endings from CRLF to LF. + +## 2.2.0 - 2023-03-29 + +### Removed + +- `laminas/laminas-dependency-plugin`. + +## 2.1 - 2022-04-26 + +### Changed + +- Prepared `composer.json` and `README.md` for the release. + ## 2.0.0 - 2020-01-30 ### Changed -* Laminas and Mezzio migration. + +- Laminas and Mezzio migration. ### Added -* Nothing + +- Nothing ### Deprecated -* Nothing + +- Nothing ### Removed -* Support + +- Support ### Fixed -* Nothing +- Nothing ## 1.0.0 - 2018-04-12 Version bump ### Added -* Update composer.json file + +- Update composer.json file ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.1 - 2017-03-10 ### Added -* Updated php file headers doc blocks + +- Updated php file headers doc blocks ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 0.1.0 - 2017-03-07 Initial tagged release ### Added -* Everything + +- Everything ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing diff --git a/README.md b/README.md index 3fd740e..3d73280 100644 --- a/README.md +++ b/README.md @@ -11,16 +11,16 @@ Documentation is available at: https://docs.dotkernel.org/dot-authentication/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-authentication) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/2.7.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/3.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/blob/2.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/blob/3.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-authentication/graph/badge.svg?token=ZBZDEA3LY8)](https://codecov.io/gh/dotkernel/dot-authentication) -[![PHPStan](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml) ## Installation @@ -32,12 +32,16 @@ composer require dotkernel/dot-authentication Please note that usually this package will be installed as a dependency to a concrete implementation, so usually you won't need to add this to your project manually. +## Upgrading + +To upgrade from version 2.x, read the [upgrade guide](https://docs.dotkernel.org/dot-authentication/v3/upgrading/). + ## AuthenticationInterface -Defines the interface that should be implemented by any authentication service to work with Dotkernel applications. -This is a result of the fact that the default packages used by Dotkernel applications that need access to the authentication service are type-hinted against this interface. +Each authentication service that works with Dotkernel applications must implement this interface. +The Dotkernel packages that use the authentication service type-hint against this interface. -Also, concrete implementations should be registered in the service manager using this interface's FQN. +Register the concrete implementation in the dependency container with the fully qualified name of this interface. ### Methods @@ -45,39 +49,97 @@ Also, concrete implementations should be registered in the service manager using public function authenticate(ServerRequestInterface $request): AuthenticationResult; ``` -This method is the implementation of the actual authentication process. +This method does the authentication. -It should extract credentials from the `$request` object (Authorization header, custom request attributes, etc.). -It should return an `AuthenticationResult` object, defined in this package, which carry the authentication status and identity on success. +It gets the credentials from the `$request` object, for example from the `Authorization` header or from request attributes. +It returns an `AuthenticationResult` object, which contains the authentication status and, on success, the identity. ```php public function challenge(ServerRequestInterface $request): ResponseInterface; ``` -This method should return a valid PSR-7 `ResponseInterface` used to notify the client or browser that it needs to authenticate first (usually using the `WWW-Authenticate` header - useful for HTTP basic and digest authentication). +This method returns a PSR-7 `ResponseInterface` that tells the client or browser to authenticate first. +Usually, this response has a `WWW-Authenticate` header, which HTTP basic and digest authentication use. ```php public function hasIdentity(): bool; public function getIdentity(): ?IdentityInterface; -public function setIdentity(IdentityInterface $identity); -public function clearIdentity(); +public function setIdentity(IdentityInterface $identity): void; +public function clearIdentity(): void; ``` -These methods are used to check if authenticated, get the authenticated identity object, force set an identity (maybe useful for auto-login) or clear an identity (logout). +Use these methods to: + +- check if there is an authenticated identity +- get the authenticated identity +- set an identity directly, for example for auto-login +- clear the identity, for example at logout ## IdentityInterface -You can use any object to represent an authenticated identity(user) as long as it implements this interface. -It requires two methods, `getId()` which should return the unique identifier of the identity, and `getName(): string` which should return a string representation of the identity (for display purposes, usually the email or username). +An authenticated identity (user) can be any object that implements this interface. +The interface has two methods: + +- `getId(): mixed` returns the unique identifier of the identity. +- `getName(): string` returns a text that shows the identity, usually the email address or the username. ## AuthenticationResult -Returned by the authentication service, on authentication success or failure. -It composes one of the predefined authentication codes, which describes the authentication status, an error message in case the authentication has failed, and the identity object on success. +The authentication service returns this object on success and on failure. +It contains: + +- one of the authentication codes, which gives the authentication status +- an error message if the authentication failed +- the identity object on success + +The codes are `int` constants: + +| Constant | Value | +| --- | --- | +| `AuthenticationResult::SUCCESS` | `1` | +| `AuthenticationResult::FAILURE` | `0` | +| `AuthenticationResult::FAILURE_INVALID_CREDENTIALS` | `-1` | +| `AuthenticationResult::FAILURE_IDENTITY_AMBIGUOUS` | `-2` | +| `AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND` | `-3` | +| `AuthenticationResult::FAILURE_UNCATEGORIZED` | `-4` | +| `AuthenticationResult::FAILURE_MISSING_CREDENTIALS` | `-5` | + +`isValid()` returns `true` when the code is greater than `0`. +Use `SUCCESS` for a successful authentication. +A custom code that is greater than `0` also counts as a success. + +To remove the identity from a result, call `setIdentity(null)`. +After this call, `hasIdentity()` returns `false`. + +## Exceptions + +All exceptions in this package implement `Dot\Authentication\Exception\ExceptionInterface`. +This interface extends `Throwable`, so you can catch all exceptions of this package with one `catch` block: + +```php +use Dot\Authentication\Exception\ExceptionInterface; + +try { + $result = $authentication->authenticate($request); +} catch (ExceptionInterface $exception) { + $message = $exception->getMessage(); +} +``` ## UnauthorizedException -Exception to be thrown when accessing content that needs authentication first. -This can be used within an application to trigger an error and do a custom action (like redirecting to a login page). -There is not a predefined way to handle this; Dotkernel packages use this exception paired with a custom error handler to handle unauthorized errors. -When using the frontend or admin applications, this is already setup among the authentication/authorization packages, and throwing an UnauthorizedException from anywhere your application, it will redirect to the login page by default. +Throw this exception when a user tries to access content that needs authentication first. +An application can use it to start a custom action, for example a redirect to a login page. +There is no predefined handler for it. +Dotkernel packages use this exception together with a custom error handler. +In the Dotkernel Frontend and Admin applications, the authentication and authorization packages already do this. +When you throw an `UnauthorizedException` in these applications, the user goes to the login page by default. + +The default exception code is `401`. +The third argument, `$previous`, accepts any `Throwable`, including an `Error`: + +```php +use Dot\Authentication\Exception\UnauthorizedException; + +throw new UnauthorizedException('You must log in first.', 401, $previous); +``` diff --git a/SECURITY.md b/SECURITY.md index 073d904..2ac7c26 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,10 +2,11 @@ ## Supported Versions -| Version | Supported | PHP Version | -|---------|--------------------|--------------------------------------------------------------------------------------------------------------------| -| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/2.7.0) | -| <= 1.x | :x: | | +| Version | Supported | PHP Version | +|---------|------------------------------|--------------------------------------------------------------------------------------------------------------------| +| 3.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/3.0.0) | +| 2.x | :lock: Security fixes only | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/2.7.0) | +| <= 1.x | :x: | | ## Reporting Potential Security Issues @@ -25,7 +26,6 @@ release prior to any public exposure; this helps protect the project's users and provides them with a chance to upgrade and/or update to protect their applications. - ## Policy If we verify a reported security vulnerability, our policy is: diff --git a/composer.json b/composer.json index 3eb8468..f2fd27c 100644 --- a/composer.json +++ b/composer.json @@ -10,14 +10,14 @@ } ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "psr/http-message": "^1.0 || ^2.0" }, "require-dev": { "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { diff --git a/docs/book/v3/configuration.md b/docs/book/v3/configuration.md new file mode 100644 index 0000000..967e3b9 --- /dev/null +++ b/docs/book/v3/configuration.md @@ -0,0 +1,3 @@ +# Configuration + +Please note that usually this package will be installed as a dependency to a concrete implementation, so usually you won't need to add this to your project manually. diff --git a/docs/book/v3/installation.md b/docs/book/v3/installation.md new file mode 100644 index 0000000..aa1c492 --- /dev/null +++ b/docs/book/v3/installation.md @@ -0,0 +1,7 @@ +# Installation + +Install `dot-authentication` by executing the following Composer command: + +```shell +composer require dotkernel/dot-authentication +``` diff --git a/docs/book/v3/overview.md b/docs/book/v3/overview.md new file mode 100644 index 0000000..f9ca5c2 --- /dev/null +++ b/docs/book/v3/overview.md @@ -0,0 +1,19 @@ +# Overview + +Core interfaces for authentication implementations. + +`dot-authentication` is Dotkernel's authentication base package that defines interfaces for authentication services to be used with Dotkernel applications. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-authentication) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-authentication/3.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-authentication)](https://github.com/dotkernel/dot-authentication/blob/3.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-authentication/graph/badge.svg?token=ZBZDEA3LY8)](https://codecov.io/gh/dotkernel/dot-authentication) +[![PHPStan](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml/badge.svg?branch=3.0)](https://github.com/dotkernel/dot-authentication/actions/workflows/static-analysis.yml) diff --git a/docs/book/v3/upgrading.md b/docs/book/v3/upgrading.md new file mode 100644 index 0000000..c01e28c --- /dev/null +++ b/docs/book/v3/upgrading.md @@ -0,0 +1,89 @@ +# Upgrading from 2.x + +Version 3.0 has changes that can break code which extends or implements classes of this package. +Code that only calls the package methods does not need changes. + +The 2.x line gets only security fixes. + +## Requirements + +Version 3.0 needs PHP 8.3 or later. +PHP 8.2 is not supported. + +## Changes that can break code + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 is not supported | Composer does not install 3.x on PHP 8.2 | Use PHP 8.3 or later | +| `ExceptionInterface` extends `Throwable` | `Class X cannot implement interface Throwable, extend Exception or Error instead` | Make the class extend `Exception` or `Error` | +| `AuthenticationResult::setIdentity()` accepts `null` | `Declaration of X::setIdentity(...) must be compatible with ...` in a subclass | Change the parameter of the subclass method to `?IdentityInterface` | +| The `AuthenticationResult` constants have the type `int` | `Type of X::SUCCESS must be compatible with ... of type int` in a subclass | Declare the constant as `public const int` | + +## Changes that do not break code + +- `UnauthorizedException::__construct()` accepts any `Throwable` as `$previous`, not only an `Exception`. + A subclass constructor can keep its signature. + +## Examples + +### A subclass of AuthenticationResult + +Before: + +```php +use Dot\Authentication\AuthenticationResult; +use Dot\Authentication\Identity\IdentityInterface; + +class MyResult extends AuthenticationResult +{ + public const FAILURE_ACCOUNT_LOCKED = -10; + + public function setIdentity(IdentityInterface $identity): void + { + parent::setIdentity($identity); + } +} +``` + +After: + +```php +use Dot\Authentication\AuthenticationResult; +use Dot\Authentication\Identity\IdentityInterface; + +class MyResult extends AuthenticationResult +{ + public const int FAILURE_ACCOUNT_LOCKED = -10; + + public function setIdentity(?IdentityInterface $identity): void + { + parent::setIdentity($identity); + } +} +``` + +A new constant in a subclass does not need a type. +Add the type to keep the constants consistent. + +### A class that implements ExceptionInterface + +Before: + +```php +use Dot\Authentication\Exception\ExceptionInterface; + +class MyException implements ExceptionInterface +{ +} +``` + +After: + +```php +use Dot\Authentication\Exception\ExceptionInterface; +use RuntimeException; + +class MyException extends RuntimeException implements ExceptionInterface +{ +} +``` diff --git a/docs/book/v3/usage.md b/docs/book/v3/usage.md new file mode 100644 index 0000000..143ac1b --- /dev/null +++ b/docs/book/v3/usage.md @@ -0,0 +1,109 @@ +# Usage + +## AuthenticationInterface + +Each authentication service that works with Dotkernel applications must implement this interface. +The Dotkernel packages that use the authentication service type-hint against this interface. + +Register the concrete implementation in the dependency container with the fully qualified name of this interface. + +### Methods + +```php +public function authenticate(ServerRequestInterface $request): AuthenticationResult; +``` + +This method does the authentication. + +It gets the credentials from the `$request` object, for example from the `Authorization` header or from request attributes. +It returns an `AuthenticationResult` object, which contains the authentication status and, on success, the identity. + +```php +public function challenge(ServerRequestInterface $request): ResponseInterface; +``` + +This method returns a PSR-7 `ResponseInterface` that tells the client or browser to authenticate first. +Usually, this response has a `WWW-Authenticate` header, which HTTP basic and digest authentication use. + +```php +public function hasIdentity(): bool; +public function getIdentity(): ?IdentityInterface; +public function setIdentity(IdentityInterface $identity): void; +public function clearIdentity(): void; +``` + +Use these methods to: + +- check if there is an authenticated identity +- get the authenticated identity +- set an identity directly, for example for auto-login +- clear the identity, for example at logout + +## IdentityInterface + +An authenticated identity (user) can be any object that implements this interface. +The interface has two methods: + +- `getId(): mixed` returns the unique identifier of the identity. +- `getName(): string` returns a text that shows the identity, usually the email address or the username. + +## AuthenticationResult + +The authentication service returns this object on success and on failure. +It contains: + +- one of the authentication codes, which gives the authentication status +- an error message if the authentication failed +- the identity object on success + +The codes are `int` constants: + +| Constant | Value | +| --- | --- | +| `AuthenticationResult::SUCCESS` | `1` | +| `AuthenticationResult::FAILURE` | `0` | +| `AuthenticationResult::FAILURE_INVALID_CREDENTIALS` | `-1` | +| `AuthenticationResult::FAILURE_IDENTITY_AMBIGUOUS` | `-2` | +| `AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND` | `-3` | +| `AuthenticationResult::FAILURE_UNCATEGORIZED` | `-4` | +| `AuthenticationResult::FAILURE_MISSING_CREDENTIALS` | `-5` | + +`isValid()` returns `true` when the code is greater than `0`. +Use `SUCCESS` for a successful authentication. +A custom code that is greater than `0` also counts as a success. + +To remove the identity from a result, call `setIdentity(null)`. +After this call, `hasIdentity()` returns `false`. + +## Exceptions + +All exceptions in this package implement `Dot\Authentication\Exception\ExceptionInterface`. +This interface extends `Throwable`, so you can catch all exceptions of this package with one `catch` block: + +```php +use Dot\Authentication\Exception\ExceptionInterface; + +try { + $result = $authentication->authenticate($request); +} catch (ExceptionInterface $exception) { + $message = $exception->getMessage(); +} +``` + +## UnauthorizedException + +Throw this exception when a user tries to access content that needs authentication first. +An application can use it to start a custom action, for example a redirect to a login page. +There is no predefined handler for it. +Dotkernel packages use this exception together with a custom error handler. +In the Dotkernel Frontend and Admin applications, the authentication and authorization packages already do this. +When you throw an `UnauthorizedException` in these applications, the user goes to the login page by default. + +The default exception code is `401`. +The third argument, `$previous`, accepts any `Throwable`, including an `Error`: + +```php +use Dot\Authentication\Exception\UnauthorizedException; + +throw new UnauthorizedException('You must log in first.', 401, $previous); +``` diff --git a/mkdocs.yml b/mkdocs.yml index 800c1d8..174d4f3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,18 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v2 + current_version: v3 versions: + - v3 - v2 nav: - Home: index.md + - v3: + - Overview: v3/overview.md + - Installation: v3/installation.md + - Configuration: v3/configuration.md + - Usage: v3/usage.md + - Upgrading from 2.x: v3/upgrading.md - v2: - Overview: v2/overview.md - Installation: v2/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index cb13649..0e1ba05 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,13 +1,17 @@ + bootstrap="vendor/autoload.php" + colors="true" + cacheDirectory=".phpunit.cache" + displayDetailsOnAllIssues="true" + failOnAllIssues="true" + beStrictAboutOutputDuringTests="true"> ./test - ./src diff --git a/src/AuthenticationInterface.php b/src/AuthenticationInterface.php index baff1f7..b3e7004 100644 --- a/src/AuthenticationInterface.php +++ b/src/AuthenticationInterface.php @@ -19,7 +19,7 @@ public function challenge(ServerRequestInterface $request): ResponseInterface; public function authenticate(ServerRequestInterface $request): AuthenticationResult; /** - * Check is there's an identity set + * Check if there is an identity set */ public function hasIdentity(): bool; diff --git a/src/AuthenticationResult.php b/src/AuthenticationResult.php index d33520d..1dc3675 100644 --- a/src/AuthenticationResult.php +++ b/src/AuthenticationResult.php @@ -8,13 +8,13 @@ class AuthenticationResult { - public const FAILURE = 0; - public const SUCCESS = 1; - public const FAILURE_INVALID_CREDENTIALS = -1; - public const FAILURE_IDENTITY_AMBIGUOUS = -2; - public const FAILURE_IDENTITY_NOT_FOUND = -3; - public const FAILURE_UNCATEGORIZED = -4; - public const FAILURE_MISSING_CREDENTIALS = -5; + public const int FAILURE = 0; + public const int SUCCESS = 1; + public const int FAILURE_INVALID_CREDENTIALS = -1; + public const int FAILURE_IDENTITY_AMBIGUOUS = -2; + public const int FAILURE_IDENTITY_NOT_FOUND = -3; + public const int FAILURE_UNCATEGORIZED = -4; + public const int FAILURE_MISSING_CREDENTIALS = -5; protected int $code; @@ -54,7 +54,7 @@ public function getIdentity(): ?IdentityInterface return $this->identity; } - public function setIdentity(IdentityInterface $identity): void + public function setIdentity(?IdentityInterface $identity): void { $this->identity = $identity; } diff --git a/src/Exception/ExceptionInterface.php b/src/Exception/ExceptionInterface.php index fbd8d1c..4debb7a 100644 --- a/src/Exception/ExceptionInterface.php +++ b/src/Exception/ExceptionInterface.php @@ -4,6 +4,8 @@ namespace Dot\Authentication\Exception; -interface ExceptionInterface +use Throwable; + +interface ExceptionInterface extends Throwable { } diff --git a/src/Exception/UnauthorizedException.php b/src/Exception/UnauthorizedException.php index e5b10d4..593873b 100644 --- a/src/Exception/UnauthorizedException.php +++ b/src/Exception/UnauthorizedException.php @@ -5,10 +5,11 @@ namespace Dot\Authentication\Exception; use Exception; +use Throwable; class UnauthorizedException extends Exception implements ExceptionInterface { - public function __construct(string $message = "", int $code = 401, ?Exception $previous = null) + public function __construct(string $message = "", int $code = 401, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); } diff --git a/test/AuthenticationInterfaceTest.php b/test/AuthenticationInterfaceTest.php deleted file mode 100644 index a4a8ba3..0000000 --- a/test/AuthenticationInterfaceTest.php +++ /dev/null @@ -1,44 +0,0 @@ -mockAuthenticationInterface = $this->createMock(AuthenticationInterface::class); - $this->identityInterfaceMock = $this->createMock(IdentityInterface::class); - $this->identityInterfaceMock->method('getId')->will($this->returnValue(10)); - $this->identityInterfaceMock->method('getName')->willReturn('username'); - $this->mockAuthenticationInterface->method('hasIdentity')->willReturn(true); - $this->mockAuthenticationInterface->method('getIdentity')->willReturn($this->identityInterfaceMock); - } - - public function testCreate(): void - { - $this->assertInstanceOf(AuthenticationInterface::class, $this->mockAuthenticationInterface); - $this->assertInstanceOf(IdentityInterface::class, $this->identityInterfaceMock); - } - - public function testFunction(): void - { - $this->assertTrue($this->mockAuthenticationInterface->hasIdentity()); - $this->assertSame('username', $this->mockAuthenticationInterface->getIdentity()->getName()); - $this->assertSame(10, $this->mockAuthenticationInterface->getIdentity()->getId()); - } -} diff --git a/test/AuthenticationResultTest.php b/test/AuthenticationResultTest.php index 0c1cfeb..8c8db00 100644 --- a/test/AuthenticationResultTest.php +++ b/test/AuthenticationResultTest.php @@ -5,46 +5,75 @@ namespace DotTest\Authentication; use Dot\Authentication\AuthenticationResult; -use Dot\Authentication\Identity\IdentityInterface; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\Authentication\Fixture\IdentityFixture; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -class AuthenticationResultTest extends TestCase +final class AuthenticationResultTest extends TestCase { - protected AuthenticationResult $subject; - protected IdentityInterface|MockObject $identityInterfaceMock; + public function testConstructorStoresAllValues(): void + { + $identity = new IdentityFixture(); + $result = new AuthenticationResult(AuthenticationResult::SUCCESS, 'valid', $identity); + + $this->assertSame(AuthenticationResult::SUCCESS, $result->getCode()); + $this->assertSame('valid', $result->getMessage()); + $this->assertSame($identity, $result->getIdentity()); + $this->assertTrue($result->hasIdentity()); + } + + public function testConstructorDefaults(): void + { + $result = new AuthenticationResult(AuthenticationResult::FAILURE); + + $this->assertSame('', $result->getMessage()); + $this->assertNull($result->getIdentity()); + $this->assertFalse($result->hasIdentity()); + } /** - * @throws Exception + * @return iterable */ - protected function setUp(): void + public static function codeProvider(): iterable { - $this->identityInterfaceMock = $this->createMock(IdentityInterface::class); - $this->identityInterfaceMock->method('getId')->will($this->returnValue(10)); - $this->identityInterfaceMock->method('getName')->willReturn('username'); - $this->subject = new AuthenticationResult(2, 'valid', $this->identityInterfaceMock); + yield 'success' => [AuthenticationResult::SUCCESS, true]; + yield 'failure' => [AuthenticationResult::FAILURE, false]; + yield 'invalid credentials' => [AuthenticationResult::FAILURE_INVALID_CREDENTIALS, false]; + yield 'identity ambiguous' => [AuthenticationResult::FAILURE_IDENTITY_AMBIGUOUS, false]; + yield 'identity not found' => [AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND, false]; + yield 'uncategorized' => [AuthenticationResult::FAILURE_UNCATEGORIZED, false]; + yield 'missing credentials' => [AuthenticationResult::FAILURE_MISSING_CREDENTIALS, false]; + yield 'custom positive code' => [2, true]; } - public function testCreate(): void + #[DataProvider('codeProvider')] + public function testIsValidDependsOnCode(int $code, bool $expected): void { - $this->assertInstanceOf(IdentityInterface::class, $this->identityInterfaceMock); + $this->assertSame($expected, (new AuthenticationResult($code))->isValid()); } - public function testAuth(): void + public function testSettersReplaceValues(): void { - $code = $this->subject->getCode(); - $message = $this->subject->getMessage(); - $name = $this->subject->getIdentity(); - $interface = $this->subject->hasIdentity(); - $isValid = $this->subject->isValid(); - - $this->assertSame(2, $code); - $this->assertSame('valid', $message); - $this->assertSame('username', $name->getName()); - $this->assertSame(10, $name->getId()); - $this->assertTrue($interface); - $this->assertEquals('valid', $message); - $this->assertTrue($isValid); + $identity = new IdentityFixture(20, 'other'); + $result = new AuthenticationResult(AuthenticationResult::FAILURE); + + $result->setCode(AuthenticationResult::SUCCESS); + $result->setMessage('changed'); + $result->setIdentity($identity); + + $this->assertSame(AuthenticationResult::SUCCESS, $result->getCode()); + $this->assertSame('changed', $result->getMessage()); + $this->assertSame($identity, $result->getIdentity()); + $this->assertTrue($result->isValid()); + } + + public function testSetIdentityAcceptsNullToClearIdentity(): void + { + $result = new AuthenticationResult(AuthenticationResult::SUCCESS, '', new IdentityFixture()); + + $result->setIdentity(null); + + $this->assertNull($result->getIdentity()); + $this->assertFalse($result->hasIdentity()); } } diff --git a/test/Exception/InvalidArgumentExceptionTest.php b/test/Exception/InvalidArgumentExceptionTest.php index 3976d47..8350bcf 100644 --- a/test/Exception/InvalidArgumentExceptionTest.php +++ b/test/Exception/InvalidArgumentExceptionTest.php @@ -4,21 +4,24 @@ namespace DotTest\Authentication\Exception; -use InvalidArgumentException; -use PHPUnit\Framework\MockObject\MockObject; +use Dot\Authentication\Exception\ExceptionInterface; +use Dot\Authentication\Exception\InvalidArgumentException; use PHPUnit\Framework\TestCase; -class InvalidArgumentExceptionTest extends TestCase +final class InvalidArgumentExceptionTest extends TestCase { - protected InvalidArgumentException|MockObject $exceptionInterfaceMock; - - public function setUp(): void + public function testCanBeCaughtAsPackageException(): void { - $this->exceptionInterfaceMock = $this->createMock(InvalidArgumentException::class); + $this->expectException(ExceptionInterface::class); + $this->expectExceptionMessage('message'); + + throw new InvalidArgumentException('message'); } - public function testCreate(): void + public function testCanBeCaughtAsSplException(): void { - $this->assertInstanceOf(InvalidArgumentException::class, $this->exceptionInterfaceMock); + $this->expectException(\InvalidArgumentException::class); + + throw new InvalidArgumentException('message'); } } diff --git a/test/Exception/RuntimeExceptionTest.php b/test/Exception/RuntimeExceptionTest.php index c600598..69f78ed 100644 --- a/test/Exception/RuntimeExceptionTest.php +++ b/test/Exception/RuntimeExceptionTest.php @@ -4,21 +4,24 @@ namespace DotTest\Authentication\Exception; +use Dot\Authentication\Exception\ExceptionInterface; use Dot\Authentication\Exception\RuntimeException; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -class RuntimeExceptionTest extends TestCase +final class RuntimeExceptionTest extends TestCase { - protected RuntimeException|MockObject $exceptionInterfaceMock; - - public function setUp(): void + public function testCanBeCaughtAsPackageException(): void { - $this->exceptionInterfaceMock = $this->createMock(RuntimeException::class); + $this->expectException(ExceptionInterface::class); + $this->expectExceptionMessage('message'); + + throw new RuntimeException('message'); } - public function testCreate(): void + public function testCanBeCaughtAsSplException(): void { - $this->assertInstanceOf(RuntimeException::class, $this->exceptionInterfaceMock); + $this->expectException(\RuntimeException::class); + + throw new RuntimeException('message'); } } diff --git a/test/Exception/UnauthorizedExceptionTest.php b/test/Exception/UnauthorizedExceptionTest.php index 62fdfb6..38cf970 100644 --- a/test/Exception/UnauthorizedExceptionTest.php +++ b/test/Exception/UnauthorizedExceptionTest.php @@ -4,21 +4,36 @@ namespace DotTest\Authentication\Exception; +use Dot\Authentication\Exception\ExceptionInterface; use Dot\Authentication\Exception\UnauthorizedException; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use TypeError; -class UnauthorizedExceptionTest extends TestCase +final class UnauthorizedExceptionTest extends TestCase { - protected UnauthorizedException|MockObject $exceptionInterfaceMock; + public function testDefaultCodeIs401(): void + { + $exception = new UnauthorizedException(); + + $this->assertSame(401, $exception->getCode()); + $this->assertSame('', $exception->getMessage()); + } - public function setUp(): void + public function testCanBeCaughtAsPackageException(): void { - $this->exceptionInterfaceMock = $this->createMock(UnauthorizedException::class); + $this->expectException(ExceptionInterface::class); + $this->expectExceptionCode(401); + + throw new UnauthorizedException(); } - public function testCreate(): void + public function testAcceptsAnyThrowableAsPrevious(): void { - $this->assertInstanceOf(UnauthorizedException::class, $this->exceptionInterfaceMock); + $previous = new TypeError('inner'); + $exception = new UnauthorizedException('Login required', 403, $previous); + + $this->assertSame('Login required', $exception->getMessage()); + $this->assertSame(403, $exception->getCode()); + $this->assertSame($previous, $exception->getPrevious()); } } diff --git a/test/Fixture/IdentityFixture.php b/test/Fixture/IdentityFixture.php new file mode 100644 index 0000000..41aaf6e --- /dev/null +++ b/test/Fixture/IdentityFixture.php @@ -0,0 +1,26 @@ +id; + } + + public function getName(): string + { + return $this->name; + } +} diff --git a/test/Identity/IdentityInterfaceTest.php b/test/Identity/IdentityInterfaceTest.php deleted file mode 100644 index 146b4cf..0000000 --- a/test/Identity/IdentityInterfaceTest.php +++ /dev/null @@ -1,36 +0,0 @@ -identityInterfaceMock = $this->createMock(IdentityInterface::class); - $this->identityInterfaceMock->method('getId')->will($this->returnValue(10)); - $this->identityInterfaceMock->method('getName')->willReturn('username'); - } - - public function testCreate(): void - { - $this->assertInstanceOf(IdentityInterface::class, $this->identityInterfaceMock); - } - - public function testFunction(): void - { - $this->assertSame('username', $this->identityInterfaceMock->getName()); - $this->assertSame(10, $this->identityInterfaceMock->getId()); - } -}