phalcon beforeExecuteRoute processing requires session and public api access control

Phanix
·
·
IPFS
·

In the architecture of phalcon, all controllers are preset to inherit from ControllerBase (app/controller/ControllerBase.php), and all request routes will go through beforeExecuteRoute first. Therefore, if you want to check the session id for all operations after the Web UI is logged in, and the system provides api for other applications to use at the same time, then you can implement beforeExecuteRoute in ControllerBase to check.

When checking, you can get the relevant information of the request through the getControllerName(), getActionName(), getParams() of the route object.

 <?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
  public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
  {
        if ( ($this->router->getControllerName() == "assets" && $this->router->getActionName() == "apisearch") || 
             ($this->router->getControllerName() == "assets" && $this->router->getActionName() == "apifacetedsearchbycategories") || 
             ($this->router->getControllerName() == "glass" && $this->router->getActionName() == "apisearch") 
           )
        {
            return;
        }
        else
        {
            if ($this->session->has("permission"))
            {
                // nothing
            }
            else
            {
            	return $this->response->redirect("login/index");
            }
        }
    }
}

Of course, if all the apis are put into a single controller, the rules to be checked are the simplest and clearest.

Original link: Phanix's Blog

CC BY-NC-ND 2.0

Like my work? Don't forget to support and clap, let me know that you are with me on the road of creation. Keep this enthusiasm together!