Skip to content

Commit

Permalink
Add basic auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Cherry-Pie committed Sep 6, 2017
1 parent 6304434 commit dd0f053
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -75,6 +75,13 @@ Route::get('/docs', function() {
});
```

Also you can force authorization prompt by adding ```apidocs.auth.basic``` middleware. Authorized identites placed under ```apidocs.auth.credentials``` config.
```php
Route::get('/docs', function() {
return ApiDocs::show();
})->middleware(['apidocs.auth.basic']);
```

To exclude some routes/classes add them to config's ```exclude```. Asterisks may be used to indicate wildcards.
```php
'exclude' => [
Expand Down
11 changes: 11 additions & 0 deletions config/apidocs.php
Expand Up @@ -21,6 +21,17 @@
//'Controllers',
],

/**
* Options for basic auth middleware.
*/
'auth' => [
'enabled' => false,

'credentials' => [
// ['username', 'password'],
],
],

/**
* Exclude specific routes from documentation. Asterisks may be used to indicate wildcards.
*/
Expand Down
34 changes: 34 additions & 0 deletions src/Http/Middleware/BasicAuth.php
@@ -0,0 +1,34 @@
<?php

namespace Yaro\ApiDocs\Http\Middleware;

class BasicAuth
{

public function handle($request, $next)
{
if ($this->isAuthorized($request)) {
return response('Unauthorized', 401, [
'WWW-Authenticate' => 'Basic',
]);
}

return $next($request);
}

private function isAuthorized($request)
{
if (!config('yaro.apidocs.auth.enabled', false)) {
return true;
}

$authorized = collect(config('yaro.apidocs.auth.credentials', []));
$credentials = [
$request->getUser(),
$request->getPassword()
];

return !$authorized->contains($credentials);
}

}
17 changes: 16 additions & 1 deletion src/ServiceProvider.php
Expand Up @@ -3,8 +3,10 @@
namespace Yaro\ApiDocs;

use Yaro\ApiDocs\Commands\BlueprintCreate;
use Yaro\ApiDocs\Http\Middleware\BasicAuth;
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;

class ServiceProvider extends \Illuminate\Support\ServiceProvider
class ServiceProvider extends IlluminateServiceProvider
{

protected $defer = false;
Expand All @@ -21,6 +23,8 @@ public function boot()
$this->commands([
'command.apidocs:blueprint-create',
]);

$this->addMiddlewareAlias('apidocs.auth.basic', BasicAuth::class);
} // end boot

public function register()
Expand All @@ -33,4 +37,15 @@ public function register()
});
} // end register

private function addMiddlewareAlias($name, $class)
{
$router = $this->app['router'];

if (method_exists($router, 'aliasMiddleware')) {
return $router->aliasMiddleware($name, $class);
}

return $router->middleware($name, $class);
}

}

0 comments on commit dd0f053

Please sign in to comment.