We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to control multiple type of user access?

In the past, I simply create a BaseController and check the session to control user to access for some pages

class BaseController extends Phalcon\Mvc\Controller
{
        public function beforeExecuteRoute()
        {
            if(!$this->session->get("user"))
            {
                $this->dispatcher->forward(array(
                    'controller' => 'login',
                    'action' => 'index'
                ));
            }
        }
}

But now the system has many types of users

for example

if $this->session->get("user")->type=='admin'

Then this user can access AdminController

while $this->session->get("user")->type=='manager'

then this user can access ManagerController

I can create many BaseController for different user types, but I think this is not a good solution, can I solve it by using one base controller?



33.8k
Accepted
answer

You don't use a controller to see if an user has access to certain controllers/actions, you use an ACL https://docs.phalcon.io/en/latest/reference/tutorial-invo.html#providing-an-acl-list

edited Sep '14

My solution to control admin user access is like below.

  • Edit route.php and config.php.
  • Create controllers/admin folder and a new ControllerBase.php.
  • Create views/admin folder and some .volt files.

route.php

...
$router->add('/admin/', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 'index',
    'action' = 'index',
]);

$router->add('/admin/:controller', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 1,
    'action' => 'index',
]);

$router->add('/admin/:controller/:action', [
    'namespace' => $config->namespace->controllersAdmin,
    'controller' => 1,
    'action' => 2,
]);
...

config.php

return new \Phalcon\Config([
    'application' => [
        'controllersDir'        => __DIR__ . '/../../app/controllers/',
        'controllersAdminDir'   => __DIR__ . '/../../app/controllers/admin/',
        ...
        'baseUri'               => '/base/',
        'baseUriAdmin'          => '/base/admin/',
    ],
    ...

app/controllers/admin/ControllerBase.php

<?php

namespace My\Namespace\Controllers\Admin;

...

class ControllerBase extends Controller
{

    public function beforeExecuteRoute($dispatcher)
    {
        $this->view->setViewsDir($this->view->getViewsDir() .'admin');
        $this->url->setBaseUri($this->config->application->baseUriAdmin);

        // Check IP address, ACL or session here.
        ...
    }
    ...
}

app/controllers/admin/MyController.php

namespace My\Namespace\Controllers\Admin;

...

class MyController extends ControllerBase
{
    ...
}