Created middleware that checks authentication

This commit is contained in:
Alejandro Celaya 2016-07-04 17:54:24 +02:00
parent dfc5bfd0f2
commit 431169eb8c
6 changed files with 123 additions and 2 deletions

View file

@ -23,6 +23,7 @@ return [
'rest' => [
'path' => '/rest',
'middleware' => [
Middleware\CheckAuthenticationMiddleware::class,
Middleware\CrossDomainMiddleware::class,
],
'priority' => 5,

View file

@ -52,6 +52,7 @@ return [
Middleware\Rest\GetVisitsMiddleware::class => AnnotatedFactory::class,
Middleware\Rest\ListShortcodesMiddleware::class => AnnotatedFactory::class,
Middleware\CrossDomainMiddleware::class => InvokableFactory::class,
Middleware\CheckAuthenticationMiddleware::class => AnnotatedFactory::class,
],
'aliases' => [
'em' => EntityManager::class,

View file

@ -0,0 +1,100 @@
<?php
namespace Acelaya\UrlShortener\Middleware;
use Acelaya\UrlShortener\Exception\InvalidArgumentException;
use Acelaya\UrlShortener\Service\RestTokenService;
use Acelaya\UrlShortener\Service\RestTokenServiceInterface;
use Acelaya\UrlShortener\Util\RestUtils;
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router\RouteResult;
use Zend\Stratigility\MiddlewareInterface;
class CheckAuthenticationMiddleware implements MiddlewareInterface
{
const AUTH_TOKEN_HEADER = 'X-Auth-Token';
/**
* @var RestTokenServiceInterface
*/
private $restTokenService;
/**
* CheckAuthenticationMiddleware constructor.
* @param RestTokenServiceInterface|RestTokenService $restTokenService
*
* @Inject({RestTokenService::class})
*/
public function __construct(RestTokenServiceInterface $restTokenService)
{
$this->restTokenService = $restTokenService;
}
/**
* Process an incoming request and/or response.
*
* Accepts a server-side request and a response instance, and does
* something with them.
*
* If the response is not complete and/or further processing would not
* interfere with the work done in the middleware, or if the middleware
* wants to delegate to another process, it can use the `$out` callable
* if present.
*
* If the middleware does not return a value, execution of the current
* request is considered complete, and the response instance provided will
* be considered the response to return.
*
* Alternately, the middleware may return a response instance.
*
* Often, middleware will `return $out();`, with the assumption that a
* later middleware will return a response.
*
* @param Request $request
* @param Response $response
* @param null|callable $out
* @return null|Response
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
// If current route is the authenticate route, continue to the next middleware
/** @var RouteResult $routeResult */
$routeResult = $request->getAttribute(RouteResult::class);
if (isset($routeResult) && $routeResult->getMatchedRouteName() === 'rest-authenticate') {
return $out($request, $response);
}
// Check that the auth header was provided, and that it belongs to a non-expired token
if (! $request->hasHeader(self::AUTH_TOKEN_HEADER)) {
return $this->createTokenErrorResponse();
}
$authToken = $request->getHeaderLine(self::AUTH_TOKEN_HEADER);
try {
$restToken = $this->restTokenService->getByToken($authToken);
if ($restToken->isExpired()) {
return $this->createTokenErrorResponse();
}
// Update the token expiration and continue to next middleware
$this->restTokenService->updateExpiration($restToken);
return $out($request, $response);
} catch (InvalidArgumentException $e) {
return $this->createTokenErrorResponse();
}
}
protected function createTokenErrorResponse()
{
return new JsonResponse([
'error' => RestUtils::INVALID_AUTH_TOKEN_ERROR,
'message' => sprintf(
'Missing or invalid auth token provided. Perform a new authentication request and send provided token '
. 'on every new request on the "%s" header',
self::AUTH_TOKEN_HEADER
),
], 401);
}
}

View file

@ -84,4 +84,15 @@ class RestTokenService implements RestTokenServiceInterface
// If credentials are not correct, throw exception
throw AuthenticationException::fromCredentials($providedUsername, $providedPassword);
}
/**
* Updates the expiration of provided token, extending its life
*
* @param RestToken $token
*/
public function updateExpiration(RestToken $token)
{
$token->updateExpiration();
$this->em->flush();
}
}

View file

@ -22,4 +22,11 @@ interface RestTokenServiceInterface
* @throws AuthenticationException
*/
public function createToken($username, $password);
/**
* Updates the expiration of provided token, extending its life
*
* @param RestToken $token
*/
public function updateExpiration(RestToken $token);
}

View file

@ -8,7 +8,8 @@ class RestUtils
const INVALID_SHORTCODE_ERROR = 'INVALID_SHORTCODE';
const INVALID_URL_ERROR = 'INVALID_URL';
const INVALID_ARGUMENT_ERROR = 'INVALID_ARGUMENT';
const INVALID_CREDENTIALS = 'INVALID_CREDENTIALS';
const INVALID_CREDENTIALS_ERROR = 'INVALID_CREDENTIALS';
const INVALID_AUTH_TOKEN_ERROR = 'INVALID_AUTH_TOKEN_ERROR';
const UNKNOWN_ERROR = 'UNKNOWN_ERROR';
public static function getRestErrorCodeFromException(Exception\ExceptionInterface $e)
@ -21,7 +22,7 @@ class RestUtils
case $e instanceof Exception\InvalidArgumentException:
return self::INVALID_ARGUMENT_ERROR;
case $e instanceof Exception\AuthenticationException:
return self::INVALID_CREDENTIALS;
return self::INVALID_CREDENTIALS_ERROR;
default:
return self::UNKNOWN_ERROR;
}