Skip to content

Commit

Permalink
Ability to set fully customizable response-handler (#59)
Browse files Browse the repository at this point in the history
* wip

* Rewrite tests in Pest

* Remove obsolete workflows, require PHP 7.4

* Fix DefaultResponseHandler namespacing

* Fix for dependencies (phpunit)

* Testing for response handlers

* Check compatibility issue (testbench)

* Update response-handler key

* Update readme
  • Loading branch information
olssonm authored Sep 16, 2022
1 parent 44a3aa4 commit a6bdd07
Show file tree
Hide file tree
Showing 14 changed files with 293 additions and 397 deletions.
13 changes: 1 addition & 12 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,14 @@ jobs:
include:
- php: 8.1
illuminate: ^9.0
phpunit: ^9.0
- php: 8.1
illuminate: ^8.0
phpunit: ^9.0
- php: 8.0
illuminate: ^8.0
phpunit: ^9.0
- php: 8.0
illuminate: ^7.0
phpunit: ^8.0
- php: 7.4
illuminate: ^7.0
phpunit: ^8.0
- php: 7.3
illuminate: ^7.0
phpunit: ^8.0
- php: 7.2
illuminate: ^6.0
phpunit: ^8.0

name: PHP ${{ matrix.php }} - Illuminate ${{ matrix.illuminate }}

Expand All @@ -46,7 +35,7 @@ jobs:
run: composer self-update --2

- name: Install dependencies
run: composer require "illuminate/support:${{ matrix.illuminate }}" "phpunit/phpunit:${{ matrix.phpunit }}" --no-interaction --no-progress --no-suggest
run: composer require "illuminate/support:${{ matrix.illuminate }}" --no-interaction --no-progress --no-suggest

- name: Execute tests
run: composer test
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# The MIT License (MIT)

Copyright (c) 2021 Marcus Olsson <[email protected]>
Copyright (c) 2022 Marcus Olsson <[email protected]>

> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
Expand Down
2 changes: 1 addition & 1 deletion README.jp.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ $ phpunit

MITライセンスです。 詳しくはこちらを見てください。[License File](LICENSE.md)

© 2021 [Marcus Olsson](https://marcusolsson.me).
© 2022 [Marcus Olsson](https://marcusolsson.me).

[ico-version]: https://img.shields.io/packagist/v/olssonm/l5-very-basic-auth.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
Expand Down
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,25 @@ Or
],
```

### Response handlers

When the authentication fails the response handler sends out an error response (see "Views and messages" for more about these options). By default the handler will be `\Olssonm\VeryBasicAuth\Handlers\DefaultResponseHandler` (see `response_handler` in `very_basic_auth.php`). You may however write your own response-logic if you so choose. The only requirement is that it implements the `\Olssonm\VeryBasicAuth\Handlers\ResponseHandler`-interface, and has an `__invoke`-method that accepts a request-object, like so:

``` php
use Illuminate\Http\Request;
use Olssonm\VeryBasicAuth\Handlers\ResponseHandler;

class CustomResponseHandler implements ResponseHandler
{
public function __invoke(Request $request)
{
// Do some stuff
return response('Custom response', 401);
}
}
```


### Views and messages

In the `very_basic_auth.php`-configuration you have the ability to set a custom view instead of a message.
Expand All @@ -116,8 +135,6 @@ In the `very_basic_auth.php`-configuration you have the ability to set a custom

If you uncomment `error_view`, the middleware will try to find your specified view. You supply this value as usual (without the `.blade.php`-extention).

*If you've upgraded to 2.1 from a previous version this key and value will be missing from your published configuration and you will have to add it yourself.*

## Usage

The middleware uses the `auth.very_basic`-filter to protect routes. You can either use `Route::group()` to protect multiple routes, or chose just to protect them individually.
Expand Down Expand Up @@ -177,7 +194,7 @@ A big thank you to the people who has contributed to this package, among others:

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

© 2021 [Marcus Olsson](https://marcusolsson.me).
© 2022 [Marcus Olsson](https://marcusolsson.me).

[ico-version]: https://img.shields.io/packagist/v/olssonm/l5-very-basic-auth.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
Expand Down
21 changes: 14 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@
}
],
"require": {
"illuminate/support": "^6.0|^7.0|^8.0|^9.0",
"php" : "^7.2|^8.0",
"illuminate/support": "^7.0|^8.0|^9.0",
"php" : "~7.4|^8.0",
"squizlabs/php_codesniffer": "^3.5"
},
"require-dev": {
"phpunit/phpunit": "^7.5|^8.0|^9.0",
"orchestra/testbench": ">=3.4.0",
"laravel/helpers": "^1.1"
"phpunit/phpunit": "^9.0",
"orchestra/testbench": ">=5.0",
"laravel/helpers": "^1.1",
"pestphp/pest": "^1.0",
"pestphp/pest-plugin-laravel": "^1.2"
},
"autoload": {
"psr-4": {
Expand All @@ -39,7 +41,7 @@
"scripts": {
"phpsniff": "vendor/bin/phpcs --standard=\"PSR12\" ./src --ignore=./src/resources/*",
"phpfix": "vendor/bin/phpcbf --standard=\"PSR12\" ./src --ignore=./src/resources/*",
"test": "vendor/bin/phpunit"
"test": "vendor/bin/pest"
},
"extra": {
"branch-alias": {
Expand All @@ -52,5 +54,10 @@
}
},
"minimum-stability": "dev",
"prefer-stable": true
"prefer-stable": true,
"config": {
"allow-plugins": {
"pestphp/pest-plugin": true
}
}
}
35 changes: 35 additions & 0 deletions src/Handlers/DefaultResponseHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Olssonm\VeryBasicAuth\Handlers;

use Illuminate\Http\Request;

class DefaultResponseHandler implements ResponseHandler
{
public function __invoke(Request $request)
{
// Build header
$header = [
'WWW-Authenticate' => sprintf(
'Basic realm="%s", charset="UTF-8"',
config('very_basic_auth.realm', 'Basic Auth')
)
];

// View
$view = config('very_basic_auth.error_view');

// If the request want's JSON, else view
if ($request->wantsJson()) {
return response()->json([
'message' => config('very_basic_auth.error_message')
], 401, $header);
} elseif (isset($view)) {
return response()->view($view, [], 401)
->withHeaders($header);
}

// Return default message
return response(config('very_basic_auth.error_message'), 401, $header);
}
}
10 changes: 10 additions & 0 deletions src/Handlers/ResponseHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Olssonm\VeryBasicAuth\Handlers;

use Illuminate\Http\Request;

interface ResponseHandler
{
public function __invoke(Request $request);
}
37 changes: 12 additions & 25 deletions src/Http/Middleware/VeryBasicAuth.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,18 @@
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Closure;
use Olssonm\VeryBasicAuth\Handlers\DefaultResponseHandler;
use Olssonm\VeryBasicAuth\Handlers\ResponseHandler;

class VeryBasicAuth
{
protected $responseHandler;

public function __construct(ResponseHandler $responseHandler)
{
$this->responseHandler = $responseHandler;
}

/**
* Handle an incoming request
*
Expand All @@ -26,8 +35,8 @@ public function handle(Request $request, Closure $next, $username = null, $passw

// Check if middleware is in use in current environment
if ($active) {
$authUsername = (empty($username)) ? config('very_basic_auth.user') : $username;
$authPassword = (empty($password)) ? config('very_basic_auth.password') : $password;
$authUsername = $username ?? config('very_basic_auth.user');
$authPassword = $password ?? config('very_basic_auth.password');

// Check for credentials
if ($request->getUser() !== $authUsername || $request->getPassword() !== $authPassword) {
Expand All @@ -46,28 +55,6 @@ public function handle(Request $request, Closure $next, $username = null, $passw
*/
private function deniedResponse(Request $request): Response
{
// Build header
$header = [
'WWW-Authenticate' => sprintf(
'Basic realm="%s", charset="UTF-8"',
config('very_basic_auth.realm', 'Basic Auth')
)
];

// View
$view = config('very_basic_auth.error_view');

// If the request want's JSON, else view
if ($request->wantsJson()) {
return response()->json([
'message' => config('very_basic_auth.error_message')
], 401, $header);
} elseif (isset($view)) {
return response()->view($view, [], 401)
->withHeaders($header);
}

// Return default message
return response(config('very_basic_auth.error_message'), 401, $header);
return ($this->responseHandler)($request);
}
}
7 changes: 7 additions & 0 deletions src/VeryBasicAuthServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Olssonm\VeryBasicAuth\Handlers\DefaultResponseHandler;
use Olssonm\VeryBasicAuth\Handlers\ResponseHandler;

class VeryBasicAuthServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -71,6 +73,11 @@ public function register()
$this->config,
'very_basic_auth'
);

$this->app->bind(
ResponseHandler::class,
config('very_basic_auth.response_handler', DefaultResponseHandler::class)
);
}

/**
Expand Down
3 changes: 3 additions & 0 deletions src/config.stub
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
'*'
],

// Response handler for the error responses
'response_handler' => \Olssonm\VeryBasicAuth\Handlers\DefaultResponseHandler::class,

// Message to display if the user "opts out"/clicks "cancel"
'error_message' => 'You have to supply your credentials to access this resource.',

Expand Down
14 changes: 14 additions & 0 deletions tests/Fixtures/CustomResponseHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Olssonm\VeryBasicAuth\Tests\Fixtures;

use Illuminate\Http\Request;
use Olssonm\VeryBasicAuth\Handlers\ResponseHandler;

class CustomResponseHandler implements ResponseHandler
{
public function __invoke(Request $request)
{
return response('Custom response', 401);
}
}
5 changes: 5 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

namespace Olssonm\VeryBasicAuth\Tests;

uses(TestCase::class)->in(__DIR__);
27 changes: 27 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Olssonm\VeryBasicAuth\Tests;

use Olssonm\VeryBasicAuth\VeryBasicAuthServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class TestCase extends OrchestraTestCase
{
protected function setUp(): void
{
parent::setUp();
}

protected function getPackageProviders($app)
{
return [
VeryBasicAuthServiceProvider::class
];
}

public static function tearDownAfterClass(): void
{
parent::tearDownAfterClass();
unlink(__DIR__ . '/../src/config.php');
}
}
Loading

0 comments on commit a6bdd07

Please sign in to comment.