Question

I am calling one function from onBootStrap() to authorize user, in that function I am using header information to verify the user.

If this is not correct, I want to stop execution here(onBootStrap()) without even calling the actual API and return some response to the user .

User should get some response because then only user can know what's the problem.

How I can return response from there?

Was it helpful?

Solution

Simply said, onBootstrap is not sufficient for this. Usually, you have two stages in your application. The first is bootstrapping, the second is running. During run you can authorize users and return responses, during bootstrap this is not possible.

The reason is simple, you might have another module overriding it's behaviour. If you stop bootstrapping after your module, you can stop the execution of these modules. It's better to move the logic to run. This run stage is defined with various listeners, of which the first is route. There isn't much going on after bootstrap and before route, so in terms of performance it's neglectable.

A code example:

use Zend\Mvc\MvcEvent;
use Zend\Json\Json;

class Module
{
    public function onBootstrap($e)
    {
        $app = $e->getApplication();
        $em  = $app->getEventManager();

        $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($app) {
            // your auth logic here

            if (!$auth) {
                $response = $e->getResponse();

                $response->setStatusCode(403);
                $response->setContent(Json::encode(array(
                   'error'   => 12345,
                   'message' => 'You are not authorized for this request',
                ));

                return $response;
            }
        }, PHP_INT_MAX);
    }
}

The listener is attached at an very early stage (PHP_INT_MAX) so the check happens as first in the complete route stage. You can also choose for quite a high number (like, 1000) so you can hook in this event before user authorization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top