I'm learning Phalcon (trying REST API in multi-module application template), and I did simple checking for each request, "does this request contain specific header" for example x-api-key
(something like ActionFilters in ASP.NET MVC).
I tried doing it with annotations
, plugins
, beforeExecuteRoute
, and beforeException
. But when I write in one of them throw new \Exception("Some exception", 500);
then Phalcon returns a blank page without an exception message and code. AFAIK this is a known bug.
I tried to do it with the dispatcher
in beforeException
:
public function beforeException($event, $dispatcher, $exception)
{
if ($exception instanceof \Phalcon\Http\Request\Exception)
{
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'showInternalServerError'
)
);
return false;
}
//...
}
and it seems that's working, but this is not an elegant solution and I'm too lazy for this :)
QUESTION: Do you have any better ideas how to do ActionFilters in PhalconPHP?
Take a look at the solution on cmoore4/phalcon-rest/HTTPException
When the application throws an HTTPError this one modifies the response object to reflect the error details and headers and send it to the output.
I like the cmoore4 way of doing many things on the REST implementation.
You can use the Match Callbacks in order to check for your api key:
Assume you have the following route:
$router->add('/api/v1', array(
'module' => 'api',
'controller' => 'index'
))
You can prepend a check to it like this:
$router->add('/api/v1', array(
'module' => 'api',
'controller' => 'index'
))
->beforeMatch(array(new AuthenticationFilter(), 'check'));
And in your custom created AuthenticationFilter, you are able to check for a valid api key:
<?php
class AuthenticationFilter
{
public function check($uri, $route)
{
$response = new \Phalcon\Http\Response();
if ($response->getHeaders()->get('X-Api-Key') != 'XYZ')
{
throw new CustomAuthenticationErrorExteption('Api Key Invalid');
// you can also just return false here and redirect to a default non-authenticated 404 response
}
else return true;
}
}
Reference
https://docs.phalconphp.com/en/latest/reference/routing.html#match-callbacks