Login +

How To ? / Using Session & Protected

Suppose you have a controller named "Private" which contains a set of actions inaccessible without being authenticated.

The only action that is accessible without being authenticated is the login action.

Best practice is to relocate checking in the init() function of the Controller, here __Private.protected.php:

public function init()
{
    parent::init();
    
    if ($this->_session->getParam("is_logged") != "true")
        $this->_generic->forward("Private", "Authentication", array(array("key"=>"Redirect", "value"=>$this->_generic->getActionId())));
}

Knowing that all actions of the controller will execute this code upstream, so we are sure that a unauthenticated member can’t access to such Action.

At the authentication action level, simply remove the call to the parent function init() to avoid infinite redirects.

public function init()
{
    #parent::init();
}

public function action()
{
    $redirect = $this->_http->getParam("Redirect");

    if ($this->_http->getParam("reload_login") == "true")
    {
        // Check credentials...
        
        if ($authorized)
        {
            $this->_session->setParam("is_logged","true");
            
            if ($this->_generic->actionIdExists($redirect))
            {
                $infos = $this->_generic->translateActionId($redirect);
                $this->_generic->forward($infos["controller"], $infos["scontroller"]);
            }
            else
                $this->_generic->forward("Private","Home");
        }
        else
            // Errors
    }
}

If the whole site need to be authenticated (an intranet for example), we could relocate the check in the init() function of the site (__site.protected.php).